Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!mit-eddie!uw-beaver!uw-june!uw-entropy!dataio!bright From: bright@dataio.Data-IO.COM (Walter Bright) Newsgroups: misc.misc,comp.lang.c Subject: Re: Printing binary (was: Re: Why college?) Message-ID: <1398@dataio.Data-IO.COM> Date: Fri, 23-Oct-87 14:21:51 EST Article-I.D.: dataio.1398 Posted: Fri Oct 23 14:21:51 1987 Date-Received: Sun, 25-Oct-87 16:53:10 EST References: <35@ateng.UUCP> <3194@sol.ARPA> <2783@xanth.UUCP> <235@snark.UUCP> <2072@watcgl.waterloo.edu> Reply-To: bright@dataio.UUCP (Walter Bright) Organization: Data I/O Corporation; Redmond, WA Lines: 59 Xref: mnetor misc.misc:1964 comp.lang.c:5105 In article <2072@watcgl.waterloo.edu> smvorkoetter@watmum.waterloo.edu (Stefan M. Vorkoetter) writes: >In article <235@snark.UUCP> eric@snark.UUCP (Eric S. Raymond) writes: >>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) > >There is a very quick way to do this using only the <<, >>, and & operators: > >#define BITS 32 /* or 16 */ > >void print_binary(n) >int n; >{ > int i; > > for(i = 0; i < BITS; i++) { > printf("%1d",(n >> (BITS - 1)) & 1); > n <<= 1; > } >} Newsgroups: misc.misc,comp.lang.c Subject: Re: Printing binary (was: Re: Why college?) Summary: Expires: References: <35@ateng.UUCP> <3194@sol.ARPA> <2783@xanth.UUCP> <235@snark.UUCP> <2072@watcgl.waterloo.edu> Sender: Reply-To: bright@dataio.UUCP (Walter Bright) Followup-To: Distribution: Organization: Data I/O Corporation; Redmond, WA Keywords: In article <2072@watcgl.waterloo.edu> smvorkoetter@watmum.waterloo.edu (Stefan M. Vorkoetter) writes: >, and & operators: <#define BITS 32 /* or 16 */ > (BITS - 1)) & 1); < n <<= 1; < } <} I simply modified the printf() format to add a %b format specifier for binary format. It added a case and 1 line of code. Also, things like %04b were gotten for free. I imagine that this is equally trivial for other compilers. Anyone know why ANSI C doesn't specify this? I wrote them a letter which they haven't replied to.