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 */
    ml = (bits & (<< i));
    /* Move lower bit to higher */
    ml <<= (31 - i*2);
    /* Get higher side bit */
    mh = (bits & (<< (31 - i)));
    /* Move higher bit to lower */
    mh >>= (31 - i*2);
    /* reset lower and higher (both) bits */
    bits &= ~(<< i);
    bits &= ~(<< (31 - i));
    /* copy swapped bits back to bits */
    bits |= (ml | mh);
  }
  return bits;
}

void print_bits(unsigned int bits, int size)
{
  int i;
  char output[33];
  memset(output, 0, sizeof(output));
  for(= size-1; i >= 0; i--)
  {
    output[size-i-1] = (bits & (<<i))? '1' : '0';
  }
  printf(output);
}
int main(int argc, char* argv[])
{
  unsigned int  bits;
  bits = 0x12345678;
  printf("Original Bits\n");
  print_bits(bits, 32);
  printf("\nReversed Bits\n");
  bits = reverse_bits(bits);
  print_bits(bits, 32);
}  

Output
Original Bits
0b00010010001101000101011001111000
Reversed Bits
0b00011110011010100010110001001000

About our authors: Team EQA

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

#