天天看点

Write an Efficient C Program to Reverse Bits of a Numberreference: Problem Definition:Solution:Code:

reference: 

http://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/

Problem Definition:

Write an Efficient C Program to Reverse Bits of a Number

Solution:

Loop through all the bits of an integer. If a bit at ith position is set in the i/p no. then set the bit at (NO_OF_BITS – 1) – i in o/p. Where NO_OF_BITS is number of bits present in the given number.

Code:

unsigned int reverseBits(unsigned int num)
{
    unsigned int  NO_OF_BITS = sizeof(num) * 8;
    unsigned int reverse_num = 0;
    int i;
    for (i = 0; i < NO_OF_BITS; i++)
    {
        if((num & (1 << i)))
           reverse_num |= 1 << ((NO_OF_BITS - 1) - i);  
   }
    return reverse_num;
}