Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!rutgers!mcnc!ece-csc!ncrcae!ncr-sd!crash!gryphon!greg From: greg@gryphon.CTS.COM (Greg Laskin) Newsgroups: misc.misc,comp.lang.c Subject: Re: Printing binary (was: Re: Why college?) Message-ID: <2030@gryphon.CTS.COM> Date: Sat, 24-Oct-87 21:19:35 EST Article-I.D.: gryphon.2030 Posted: Sat Oct 24 21:19:35 1987 Date-Received: Tue, 27-Oct-87 02:27:38 EST References: <35@ateng.UUCP> <3194@sol.ARPA> <2783@xanth.UUCP> <235@snark.UUCP> <2072@watcgl.waterloo.edu> Reply-To: greg@gryphon.CTS.COM (Greg Laskin) Organization: Trailing Edge Technology, Redondo Beach, CA Lines: 55 Xref: mnetor misc.misc:1970 comp.lang.c:5139 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); ^^^^^^^^^^^^^^^ not a constant expression > n <<= 1; > } >} #define BitsPerUnit 8 void print_binary(n) int n; { int i; for (i=0; i < (sizeof (int) * BitsPerUnit) ; ++i,n<<=1) putchar(( n & (1<<(sizeof (int) * BitsPerUnit) -1)) ? '1' : '0'); /* a constant expression */ } Using the constant expression is "quick"er. On my 16 bit machine, the compiler can resolve the expression to: putchar((n & 0x8000 ) ? '1' : '0'); at compile time instead of shifting n BITS bits BITS times at run time. Using putchar() instead of printf() is picking a nit. Comments on portability to other environments solicited (by email please). -- Greg Laskin "When everybody's talking and nobody's listening, how can we decide?" INTERNET: Greg.Laskin@gryphon.CTS.COM UUCP: {hplabs!hp-sdd, sdcsvax, ihnp4}!crash!gryphon!greg UUCP: {philabs, scgvaxd}!cadovax!gryphon!greg