Thursday, July 9, 2015

Reverse bits in a word


Write a function to reverse bits in an integer

Bonus points for handling integers of all sizes

My Solution

Loop through half of the integer
Compare each bit with distance n from the least significant bit with the bit that is n distance from the Most Significant Bit
if they are the same do nothing
if they are different both the bits are toggled
end loop

unsigned int ReverseBits(unsigned int x)
{
unsigned int n = x;
int y = sizeof(int)*8;
int mask1, mask2;

for (int index = 0; index < y/2; index++)
{
mask1 = 1 << index;
mask2 = 1 << (y - index - 1);

// if match do nothing
if (((x & mask1)>>index) == ((x & mask2)>>(y-index-1)))
{
}
else
{
x ^= 1 << index;
x ^= 1 << (y - index - 1);
}
}

return x;
}

No comments:

Post a Comment