Write an Efficient C Program to Reverse Bits of a Number
Also Reverse the byte sequence of a number in both 16 bit and 32 bit machine.For example:
For a number )x1234 it should return 0x3412
NOTE: ORing 0 with x gives x
// Reverse byte order (16-bit) UInt16 ReverseBytes(UInt16 value) { return (UInt16)((value & 0xFFU) << 8 | (value & 0xFF00U) >> 8); }
UInt32 ReverseBytes(UInt32 value) { return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 | (value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24; }
http://www.geeksforgeeks.org/archives/726
ReplyDeleteLoop 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.
ReplyDeleteunsigned int ReverseBits_Easy(unsigned int num)
ReplyDelete{
unsigned int NO_OF_BITS = sizeof(num) * 8;
unsigned int reverse_num = 0, i, temp;
for (i = 0; i < NO_OF_BITS; i++)
{
temp = (num & (1 << i));
if(temp)
reverse_num |= (1 << ((NO_OF_BITS - 1) - i));
}
return reverse_num;
}
Advanced Method----------
ReplyDeleteThe idea is to keep putting set bits of the num in reverse_num until num becomes zero. After num becomes zero, shift the remaining bits of reverse_num.
unsigned int ReverseBits_Advanced(unsigned int num)
ReplyDelete{
unsigned int count = sizeof(num) * 8 - 1;
unsigned int reverse_num = num;
num >>= 1;
while(num)
{
reverse_num <<= 1;
reverse_num |= num & 1;
num >>= 1;
count--;
}
reverse_num <<= count;
return reverse_num;
}