algorithm to convert N into base 3 wanted!
William E. Davidsen Jr
davidsen at steinmetz.ge.com
Thu Aug 25 05:47:57 AEST 1988
In article <650003 at hpcilzb.HP.COM> tedj at hpcilzb.HP.COM (Ted Johnson) writes:
>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).
This is one of the problems given in _intro to programming_ courses, but
here's the C code for any positive integer to any base 1..16. Note I'm
typing it in, so look for typos before you tell me it doesn't work.
print_to_base(val, base)
int val, base;
{
register int a;
static char *digits = "0123456789ABCDEF";
if (a = val/base) print_to_base(a, base);
putchar(digits[val%base]);
}
I usually let students modify it to handle negative values, fixed width,
etc. I use a form of it to output things to binary, writing to an
internal string and returning the address of the string.
Disclamer: at least ten people will tell me there's a better way to do
the general case, or to do the base three case only. At least twice as
many people will tell me there's a better way than tried to help the
original poster. If my company has an opinion they don't tell me.
--
bill davidsen (wedu at ge-crd.arpa)
{uunet | philabs | seismo}!steinmetz!crdos1!davidsen
"Stupidity, like virtue, is its own reward" -me
More information about the Comp.lang.c
mailing list