Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!utgpu!water!watmath!watcgl!watmum!smvorkoetter From: smvorkoetter@watmum.UUCP Newsgroups: misc.misc,comp.lang.c Subject: Re: Printing binary (was: Re: Why college?) Message-ID: <2072@watcgl.waterloo.edu> Date: Tue, 20-Oct-87 09:52:54 EDT Article-I.D.: watcgl.2072 Posted: Tue Oct 20 09:52:54 1987 Date-Received: Thu, 22-Oct-87 23:43:34 EDT References: <35@ateng.UUCP> <3194@sol.ARPA> <2783@xanth.UUCP> <235@snark.UUCP> Sender: daemon@watcgl.waterloo.edu Reply-To: smvorkoetter@watmum.waterloo.edu (Stefan M. Vorkoetter) Organization: U. of Waterloo, Ontario Lines: 20 Xref: utgpu misc.misc:1827 comp.lang.c:4809 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; } }