home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!magnus.acs.ohio-state.edu!usenet.ins.cwru.edu!agate!doc.ic.ac.uk!anb
- From: anb@doc.ic.ac.uk (A N Burton)
- Newsgroups: comp.lang.c
- Subject: Re: How to print an integer as binary?
- Date: 6 Nov 1992 14:34:21 GMT
- Organization: Department of Computing, Imperial College, University of London, UK.
- Lines: 84
- Distribution: world
- Message-ID: <1ddvpdINNc3d@frigate.doc.ic.ac.uk>
- References: <1992Nov4.180622.6568@csd.uwe.ac.uk> <1dbpe8INNcop@frigate.doc.ic.ac.uk> <a_rubin.720993308@dn66>
- NNTP-Posting-Host: mfast.doc.ic.ac.uk
-
-
- Many thanks to those who pointed out errors etc in my code.
-
- What I hope are more correct versions of the functions appear below.
-
- Ariel BURTON
-
-
-
-
- #include <stdio.h>
- #include <limits.h>
-
-
- void
- aux1( long x ){
- if( x ){
- aux1( x / 2 );
- putchar( (x%2) ? '1' : '0' );
- }
- }
-
- void
- PrintBinary1( long x ){
- if( 0 == x )
- putchar( '0' );
- else{
- if ( x < 0 )
- putchar( '-' );
- else
- x = -x;
- aux1( x );
- }
- }
- #define MAX_SIZE ( CHAR_BIT * sizeof( long ) )
- void
- PrintBinary2( long x ){
- char buff[ MAX_SIZE+1 ];
- int i;
-
- if( ! x )
- putchar( '0' );
- else{
- if( x < 0 )
- putchar( '-' );
- else
- x = -x ;
-
- buff[ i = MAX_SIZE ] = '\0';
- for( ; x ; x /= 2 )
- buff[ --i ] = (x%2) ? '1' : '0';
-
- printf( "%s", buff+i );
- }
- }
-
- void
- PrintBinary3( long x ){
- unsigned long mask = (((unsigned long)(-1)) >> 1 ) + 1;
-
- if( ! x )
- putchar( '0' );
- else{
- 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' );
- }
-