training

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

reverseBits.c (732B)


      1 /* Exercise 10.17 */
      2 
      3 #include <stdio.h>
      4 
      5 typedef unsigned u_int;
      6 
      7 void pbits(u_int n);
      8 u_int reverseBits(u_int num);
      9 
     10 int main(void)
     11 {
     12    u_int num;
     13 
     14    printf("Give me a number: ");
     15    scanf("%u", &num);
     16 
     17    printf("before:\t");
     18    pbits(num);
     19    putchar('\n');
     20 
     21    printf("after:\t");
     22    pbits( reverseBits(num) );
     23    putchar('\n');
     24 
     25    return 0;
     26 } /* E0F main */
     27 
     28 /* Print a number in bits */
     29 void pbits(u_int n)
     30 {
     31    u_int mask = 1 << 31;
     32    int i;
     33 
     34    for(i = 1; i <= 32; i++) {
     35       printf("%u", n & mask ? 1 : 0);
     36 
     37       if( !(i % 8) )
     38          putchar(' ');
     39 
     40       n <<= 1;
     41    }
     42 
     43 } /* eof pbits() */
     44 
     45 /* Reverse the bits order to an u_int number */
     46 u_int reverseBits(u_int num)
     47 {
     48    return ~num;
     49 } /* eof reverseBits()*/
     50