Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!seismo!sundc!pitstop!sun!decwrl!spar!hunt From: hunt@spar.SPAR.SLB.COM (Neil Hunt) Newsgroups: comp.lang.c Subject: Re: Printing binary (was: Re: Why college?) Message-ID: <1646@spar.SPAR.SLB.COM> Date: Fri, 23-Oct-87 13:44:24 EST Article-I.D.: spar.1646 Posted: Fri Oct 23 13:44:24 1987 Date-Received: Sun, 25-Oct-87 18:38:38 EST References: <35@ateng.UUCP> <3194@sol.ARPA> <2783@xanth.UUCP> <235@snark.UUCP> <2072@watcgl.waterloo.edu> Reply-To: hunt@spar.UUCP (Neil Hunt) Organization: Schlumberger Palo Alto Research - CASLAB Lines: 40 This is crying out for recursion: /* * print_binary: * Prints `value' in binary with `bits' digits. */ void print_binary(value, bits) int value, bits; { if(--bits > 0) print_binary(value >> 1, bits); putchar((value & 0x1) + '0'); } To print without extra leading zeros or ones (that is if the value is positive, print a single 0 then the actual number, if it is negative, print a single 1 and then the actual number): /* * print_normalised_binary: * Prints `value' in binary with sign bit in normalised position. * Assumes a sign extending '>>'. */ void print_normalised_binary(value) int value; { if(value != 0 && value != -1) print_normalised_binary(value >> 1); putchar((value & 0x1) + '0'); } Exercise 1a: rewrite the above functions for printing hexadecimal and octal Neil/.