home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ukma!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: 5 Nov 1992 18:33:44 GMT
- Organization: Department of Computing, Imperial College, University of London, UK.
- Lines: 86
- Distribution: world
- Message-ID: <1dbpe8INNcop@frigate.doc.ic.ac.uk>
- References: <1992Nov4.180622.6568@csd.uwe.ac.uk>
- NNTP-Posting-Host: mfast.doc.ic.ac.uk
-
- In article <1992Nov4.180622.6568@csd.uwe.ac.uk> th2_oate@csd.uwe.ac.uk (Tom Oates) writes:
- >Assuming that:-
- >
- >int i = 203;
- >
- >How do I display 'i' as 11001011?
- >
- >
- >
- >
- >--
- >******************************************************************************
- >* Tom Oates (Univ. of West of England) * DISCLAIMER:I speak only for myself. *
- >* Email to: th2_oate@uk.ac.uwe.csd * PGP 2.0 Key available upon request. *
- >******************************************************************************
-
-
- The program appearing below gives three possible solutions; the first is for
- those favouring recursion, the other two use loops. The second scans the
- number from right to left, and therefore uses an array to hold the partial
- results. Solution three scans from left to right and thus outputs as the
- binary form is generated.
-
-
- Ariel BURTON
-
-
-
- #include <stdio.h>
-
-
- void
- PrintBinary1( long x ){
- if ( x < 0 ){
- putchar( '-' );
- PrintBinary1( -x );
- }
- else if( x < 2 )
- putchar( '0'+x );
- else{
- PrintBinary1( x >> 1 );
- putchar( '0'+( x & 1 ) );
- }
- }
- #define MAX_SIZE 32
- 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 )
- buff[ --i ] = '0'+ (x&1);
-
- printf( "%s", buff+i );
- }
-
- void
- PrintBinary3( long x ){
- unsigned long mask = 1 << (8*sizeof(unsigned long) - 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' );
- }
-