home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ferkel.ucsb.edu!taco!gatech!swrinde!zaphod.mps.ohio-state.edu!usc!news.service.uci.edu!beckman.com!dn66!a_rubin
- Newsgroups: comp.lang.c
- Subject: Re: How to print an integer as binary?
- Message-ID: <a_rubin.720993308@dn66>
- From: a_rubin@dsg4.dse.beckman.com (Arthur Rubin)
- Date: 5 Nov 92 19:55:08 GMT
- References: <1992Nov4.180622.6568@csd.uwe.ac.uk> <1dbpe8INNcop@frigate.doc.ic.ac.uk>
- Organization: Beckman Instruments, Inc.
- Nntp-Posting-Host: dn66.dse.beckman.com
- Lines: 86
-
- In <1dbpe8INNcop@frigate.doc.ic.ac.uk> anb@doc.ic.ac.uk (A N Burton) writes:
-
-
- >#include <stdio.h>
-
-
- >void
- >PrintBinary1( long x ){
- > if ( x < 0 ){
- > putchar( '-' );
- > PrintBinary1( -x );
-
- usually infinite recursion on a 2s complement machine if x = LONG_MIN;
- can be easily fixed only by having a PrintBinary1U (unsigned long)
-
- > }
- > else if( x < 2 )
- > putchar( '0'+x );
- > else{
- > PrintBinary1( x >> 1 );
- > putchar( '0'+( x & 1 ) );
- > }
- >}
- >#define MAX_SIZE 32
-
- perhaps:
-
- #include <limits.h>
- #define MAX_SIZE (CHAR_BIT * sizeof(long))
-
- >void
- >PrintBinary2( long x ){
- > char buff[ MAX_SIZE+1 ];
- > int i;
-
- > if( x < 0 ){
- > x = -x ;
- > putchar( '-' );
- > }
-
- > buff[ i = MAX_SIZE ] = '\0';
- > for( ; x ; x >>= 1 )
-
- loops forever if x is LONG_MIN, as -LONG_MIN is usually LONG_MIN;
- can be fixed by copying x to an unsigned long and using it.
-
- > buff[ --i ] = '0'+ (x&1);
-
- > printf( "%s", buff+i );
- >}
-
- >void
- >PrintBinary3( long x ){
- > unsigned long mask = 1 << (8*sizeof(unsigned long) - 1);
- ^
- \CHAR_BIT
-
- or, the clean ANSI version:
-
- unsigned long mask = (((unsigned long)(-1)) >> 1) + 1;
-
- > if( x < 0 ){
- > putchar( '-' );
- > x = -x;
- > }
-
- > for( ; ! (x & mask) ; mask >>= 1 )
- > ;
-
- > for( ; mask ; mask >>= 1 )
- > putchar( x & mask ? '1' : '0' );
- >}
-
- >main( int argc, char *argv[] ){
- > PrintBinary1( atol(argv[1] ) );
- > putchar( '\n' );
- > PrintBinary2( atol(argv[1] ) );
- > putchar( '\n' );
- > PrintBinary3( atol(argv[1] ) );
- > putchar( '\n' );
- >}
- --
- Arthur L. Rubin: a_rubin@dsg4.dse.beckman.com (work) Beckman Instruments/Brea
- 216-5888@mcimail.com 70707.453@compuserve.com arthur@pnet01.cts.com (personal)
- My opinions are my own, and do not represent those of my employer.
- My interaction with our news system is unstable; please mail anything important.
-