training

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

portablepbits.c (526B)


      1 /* Exercise 10.18 */
      2 
      3 #include <stdio.h>
      4 
      5 typedef unsigned u_int;
      6 
      7 void pbits(u_int n);
      8 
      9 
     10 int main(void)
     11 {
     12    u_int num;
     13 
     14    num = 12345;
     15 
     16    pbits(num);
     17    putchar('\n');
     18 
     19    return 0;
     20 } /* E0F main */
     21 
     22 /* Print a number in bits */
     23 void pbits(u_int n)
     24 {
     25    u_int mask = 1 << 31;
     26    int i;
     27 
     28    for(i = 1; i <= 32; i++) {
     29       if( sizeof(int) == 4 )
     30          printf("%u", n & mask ? 1 : 0);
     31       else
     32 	 printf("%ul", n & mask ? 1 : 0);
     33 
     34       if( !(i % 8) )
     35          putchar(' ');
     36 
     37       n <<= 1;
     38    }
     39 
     40 } /* eof pbits() */
     41 
     42