Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!seismo!sundc!pitstop!sun!amdcad!ames!hao!boulder!sunybcs!rutgers!dayton!umn-cs!herndon From: herndon@umn-cs.UUCP (Robert Herndon) Newsgroups: comp.lang.c Subject: Re: Printing binary Message-ID: <2488@umn-cs.UUCP> Date: Tue, 27-Oct-87 17:21:46 EST Article-I.D.: umn-cs.2488 Posted: Tue Oct 27 17:21:46 1987 Date-Received: Wed, 4-Nov-87 05:47:35 EST References: <35@ateng.UUCP> <3194@sol.ARPA> <2783@xanth.UUCP> <235@snark.UUCP> <247@snark.UUCP> Organization: University of Minnesota, Minneapolis Lines: 55 Summary: A generic recursive, sprintf compatible int to ascii conversion routine. In article <247@snark.UUCP>, eric@snark.UUCP (Eric S. Raymond) writes: > In article <1646@spar.SPAR.SLB.COM>, hunt@spar.SPAR.SLB.COM (Neil Hunt) writes: > > This is crying out for recursion: [followed by a print_binary implementation] > > Now that's more elegant than my internal-to-hex-nybbles-to binary hack (which > I posted mostly for its giggle value). It also avoids the flaw of the second > proposal (which is nonportable, requiring this ugly #define in source for the > machine's word length). > > But your trick can't be generalized to do the sprintf analogue. GONG! This isn't exactly the ticket, but it shows how it can be done. (This is a library routine I've used for years.) -----------------------------------------------Cut Here. #include /* * itoa(n, b, s) * Puts base b character representation of n into s, terminates * representation with null. Returns pointer to null at end of * representation. * * Works for n >= 0, 2 <= b <= 32. * Robert Herndon, May 1977. */ char *itoa(n, b, s) int n, b; char *s; { if(n/b != 0) { s = itoa(n/b, b, s); } *s++ = "0123456789ABCDEFGHIJKLMNOPQRSTUV"[n%b]; *s = '\0'; return s; } main(ac, av) int ac; char *av[]; { char result[50]; if(ac < 3) { fprintf(stderr, "Usage: itoa "); exit(1); } itoa(atoi(av[1]), atoi(av[2]), result); printf("%s(10) = %s(%s)\n", av[1], result, av[2]); } -- Robert Herndon Dept. of Computer Science, ...!ihnp4!umn-cs!herndon Univ. of Minnesota, herndon@umn-cs.ARPA 136 Lind Hall, 207 Church St. SE herndon.umn-cs@csnet-relay.ARPA Minneapolis, MN 55455