training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

fig10_07_mod.c (1009B)


      1 /* Exercise 10.11 */
      2 
      3 /* Fig. 10.7: fig10_07.c
      4    Printing an unsigned integer in bits */
      5 #include <stdio.h>
      6 
      7 typedef unsigned u_int; /* Portable definition */
      8 void displayBits( u_int value ); /* prototype */
      9 
     10 int main(void)
     11 { 
     12    u_int x; /* variable to hold user input */
     13 
     14    printf( "Enter an unsigned integer: " );
     15    scanf( "%lu", &x );
     16 
     17    displayBits( x );
     18    
     19    return 0; /* indicates successful termination */
     20 
     21 } /* end main */
     22 
     23 /* display bits of an unsigned integer value */
     24 void displayBits( u_int value )
     25 { 
     26    u_int c; /* counter */
     27 
     28    /* define displayMask and left shift 31 bits */
     29    u_int displayMask = 1 << 31; 
     30 
     31    printf( "%10lu = ", value );
     32 
     33    /* loop through bits */ 
     34    for ( c = 1; c <= 32; c++ ) { 
     35       putchar( value & displayMask ? '1' : '0' );
     36       value <<= 1; /* shift value left by 1 */   
     37 
     38       if ( c % 8 == 0 ) { /* output space after 8 bits */
     39          putchar( ' ' );
     40       } /* end if */
     41 
     42    } /* end for */
     43 
     44    putchar( '\n' );
     45 } /* end function displayBits */
     46