Path: utzoo!attcan!uunet!lll-winken!lll-tis!helios.ee.lbl.gov!pasteur!ucbvax!decwrl!megatest!djones From: djones@megatest.UUCP (Dave Jones) Newsgroups: comp.lang.c Subject: Re: algorithm to convert N into base 3 wanted! Message-ID: <740@goofy.megatest.UUCP> Date: 23 Aug 88 22:19:09 GMT References: <650003@hpcilzb.HP.COM> Organization: Megatest Corporation, San Jose, Ca Lines: 54 From article <650003@hpcilzb.HP.COM>, by tedj@hpcilzb.HP.COM (Ted Johnson): > Does anyone know of an algorithm to convert a positive integer N into > its base 3 representation? (e.g., 14 in base 10 is 112 in base 3). > > Any textbook/journal pointers are appreciated! (Source code is > appreciated even more :-) > > -Ted /* Always happy to help, (if it's this easy). */ #define THREES_MAX 21 /* A number of chars big enough to represent ** any int in base three. Assuming here 32 bit ints. */ main(argc, argv) char** argv; { char threes_rep[THREES_MAX]; base3(atoi(argv[1]), threes_rep); printf("%s\n", threes_rep); exit(0); } #define digit(num) ((char)(num + '0')) base3(num, result) int num; char* result; { int power = 0; char backwards[THREES_MAX]; while(num != 0) { backwards[power++] = digit(num % 3); num = num / 3; } { int rpower = 0; while(--power >= 0) { result[rpower++] = backwards[power]; } result[rpower] = '\0'; } }