A 32 bit number is a series of bits from 0 to 31. We can access each bit via shifting operation. We take an unit 1 as reference min value to traverse bits. When we shift 1 by 0 at right, it positioned at 0th position and if we AND it with bits it gives 0th position value. ANDing with 1 gives us the exact value. If the bit is 1 then we get 1 else 0 will result as 0 only. Now we shift to next position i.e. shift right by 1 and AND with bits. This way we can iterate till 31th bit and obtain each bits.

Previous steps shows how to access each bit and how to iterate through bits. Now reversing bits are more complex. We need to get bit 0 and bit 31 and swap it and save it again back to bitmask. In the next iteration we access 1 and 30 th bit and swap. In this way we swap till the middle position.

#include <stdio.h>
unsigned int reverse_bits(unsigned int bits)
{
  int i;
  unsigned int ml,mh;
  for (= 0; i < 32/2; i++)
  {
    /* Get lower side bit */
10      ml = (bits & (<< i));
11      /* Move lower bit to higher */
12      ml <<= (31 - i*2);
13      /* Get higher side bit */
14      mh = (bits & (<< (31 - i)));
15      /* Move higher bit to lower */
16      mh >>= (31 - i*2);
17      /* reset lower and higher (both) bits */
18      bits &= ~(<< i);
19      bits &= ~(<< (31 - i));
20      /* copy swapped bits back to bits */
21      bits |= (ml | mh);
22    }
23    return bits;
24  }
25 
26  void print_bits(unsigned int bits, int size)
27  {
28    int i;
29    char output[33];
30    memset(output, 0, sizeof(output));
31    for(= size-1; i >= 0; i--)
32    {
33      output[size-i-1] = (bits & (<<i))? '1' : '0';
34    }
35    printf(output);
36  }
37  int main(int argc, char* argv[])
38  {
39    unsigned int  bits;
40    bits = 0x12345678;
41    printf("Original Bits\n");
42    print_bits(bits, 32);
43    printf("\nReversed Bits\n");
44    bits = reverse_bits(bits);
45    print_bits(bits, 32);
46  }  
47 
Output
Original Bits
0b00010010001101000101011001111000
Reversed Bits
0b00011110011010100010110001001000

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

logical operators, logical vs bitwise operators, logical and bitwise or, bit shifting, obtain bit mask, reverse bits, swap bits, bit set, reset/clear, toggle, xor operator, bitwise shifting,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan