First of all, it doesn't invert the bits, it reverses them (and only those between the rightmost bit and the leftmost bit which is set to 1).
Second, here is how it works:
int binaryReverse(int toReverse)
{
int reversed = 0;
while (toReverse > 0)
{
reversed *= 2; // shift the output one bit to the left
reversed += toReverse % 2; // set the rightmost bit in the output to the value of the rightmost bit in the input
toReverse /= 2; // shift the input one bit to the right
}
return reversed;
}
Third, here is a possibly more readable version (though it has to take the input as unsigned
):
int binaryReverse(unsigned int toReverse)
{
int reversed = 0;
while (toReverse > 0)
{
reversed <<= 1; // shift the output one bit to the left
reversed |= toReverse & 1; // set the rightmost bit in the output to the value of the rightmost bit in the input
toReverse >>= 1; // shift the input one bit to the right
}
return reversed;
}