Path: utzoo!utgpu!water!watmath!clyde!att!pacbell!lll-tis!helios.ee.lbl.gov!nosc!ucsd!ucsdhub!esosun!seismo!uunet!steinmetz!davidsen From: davidsen@steinmetz.ge.com (William E. Davidsen Jr) Newsgroups: comp.lang.c Subject: Re: algorithm to convert N into base 3 wanted! Message-ID: <11966@steinmetz.ge.com> Date: 24 Aug 88 19:47:57 GMT References: <650003@hpcilzb.HP.COM> Reply-To: davidsen@crdos1.UUCP (bill davidsen) Organization: General Electric CRD, Schenectady, NY Lines: 30 In article <650003@hpcilzb.HP.COM> tedj@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@ge-crd.arpa) {uunet | philabs | seismo}!steinmetz!crdos1!davidsen "Stupidity, like virtue, is its own reward" -me