Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!cmcl2!rutgers!cbmvax!snark!eric From: eric@snark.UUCP (Eric S. Raymond) Newsgroups: misc.misc,comp.lang.c Subject: Printing binary (was: Re: Why college?) Message-ID: <235@snark.UUCP> Date: Mon, 19-Oct-87 12:34:46 EDT Article-I.D.: snark.235 Posted: Mon Oct 19 12:34:46 1987 Date-Received: Wed, 21-Oct-87 00:33:22 EDT References: <35@ateng.UUCP> <3194@sol.ARPA> <2783@xanth.UUCP> Organization: Benevolent Space Xist Retirement Home Lines: 39 Summary: Here's a neat hack Xref: mnetor misc.misc:1950 comp.lang.c:5034 In article <148@artsvax.UUCP>, mike@artsvax.UUCP (Michael Czeiszperger) writes: > The variable five is certainly stored in binary, even though it represents > an integer. A more plausible interpretation in a test situation would be > to print each of the binary bits out in ascii, so that the output for an > integer 5 (assuming a large machine where an integer is 4 bytes) would be: > > 00000000000000000000000000000101 I thought about the standard ways to do this, (essentially, crack the sucker into powers-of-two internally via repeated integer-divide and modulo operations) went *ugh*, and then had a flash that gave me an amusing alternate solution. Here it is: (warning! this is untested and off-the-cuff) #include "stdio.h" void bprint(n, fp) /* print n in binary to given fp */ int n; FILE *fp; { static char *nybbles = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111", }; static char hexdigits = "0123456789abcdef"; char foobuf[BUFSIZ], *cp; /* BUFSIZ from stdio.h */ (void) sprintf(cp = foobuf, "%x", n); while (*cp) (void) fputs(nybbles[strchr(hexdigits, *cp++) - hexdigits], fp); } Le voila! Let the C libraries do the work whenever you can, I always say... -- Eric S. Raymond UUCP: {{seismo,ihnp4,rutgers}!cbmvax,sdcrdcf!burdvax,vu-vlsi}!snark!eric Post: 22 South Warren Avenue, Malvern, PA 19355 Phone: (215)-296-5718