Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!utgpu!water!watmath!clyde!rutgers!iuvax!pur-ee!uiucdcs!uxc.cso.uiuc.edu!uxe.cso.uiuc.edu!mcdonald From: mcdonald@uxe.cso.uiuc.edu.UUCP Newsgroups: comp.lang.c Subject: Re: Printing binary (was: Re: Why colle Message-ID: <47000021@uxe.cso.uiuc.edu> Date: Tue, 27-Oct-87 12:23:00 EST Article-I.D.: uxe.47000021 Posted: Tue Oct 27 12:23:00 1987 Date-Received: Sat, 31-Oct-87 01:45:17 EST References: <235@snark.UUCP> Lines: 46 Nf-ID: #R:snark.UUCP:235:uxe.cso.uiuc.edu:47000021:000:1146 Nf-From: uxe.cso.uiuc.edu!mcdonald Oct 27 11:23:00 1987 ********this is a repost***** ********the notes system bounced this with a message about "network congestion" has this happened to you?*********** >#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); >} Arrgh gasp complicated! perhaps (going to stdout, and for longs, but you get the idea): #include bprint(number) long number; { unsigned long mask; for (mask = ~( (~(unsigned long)1l) >> 1); mask != 0 ; mask >>= 1) putchar((((unsigned long)number & mask) != 0l) + '0'); } On paper this even works on 1's complements machines, although I haven't tried it except on 2's complement. Note that nowhere is the word size explicitly needed. Doug McDonald