I am new to bit manipulation. My friend recently asked me this in an interview. Given an array of bytes Eg: 1000100101010101 | 001010011100 We need to flip it two bits at a time horizontally inplace. So the new array should be: 1000 | 0101 and so on.
and so on. I think we start from the middle (marked by | here) and continue our way outwards taking two bits at a time. I know how to reverse single bits in a number at a time like this:
unsigned int reverse(unsigned int num)
{
unsigned int x = sizeof(num) * 8;
unsigned int reverse_num = 0, i, temp;
for (i = 0; i < x; i++)
{
temp = (num & (1 << i));
if(temp)
reverse_num |= (1 << ((x - 1) - i));
}
return reverse_num;
}
But I wonder how can we reverse two bits efficiently inplace. Thanks in advance.