Path: utzoo!utgpu!water!watmath!clyde!ima!haddock!suitti From: suitti@haddock.ima.isc.com (Steve Uitti) Newsgroups: comp.sys.mac.programmer Subject: Re: base 10 --> base 3 ... Message-ID: <6433@haddock.ima.isc.com> Date: 24 Aug 88 16:30:37 GMT References: <730059@hpcilzb.HP.COM> Reply-To: suitti@haddock.ima.isc.com (Steve Uitti) Organization: Interactive Systems, Boston Lines: 29 In article <730059@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). There are perhaps an infinite number of ways to do this. Here's one. The digits are produced in reverse order, so recursion is used to put them on the stack for First In Last Out (reverse) ordering. The "%" (remainder) operator in C is seldom used, as is indexing into a string literal. Note that the input "num" does not really have a radix. Most machines represent integers using binary, but if integers were Binary Coded Decimal, this would still work. /* print num in radix, lead zero suppressed */ void pnum(num, radix) int num, radix; { int a; a = num % radix; /* remainder */ num /= radix; if (num != 0) pnum(num, radix); /* call self to finish */ printf("%c", "0123456789abcdef"[a]); } main() { pnum(14, 3); printf("\n"); } /* test - produces 112 */ Stephen.