Question

I recently stumbled upon this function which inverts binary representation of even numbers,but I'm not able to understand the logic behind the code?

int binaryReverse(int toReverse) {

     int reversed = 0;
     while(toReverse > 0) {
             reversed *= 2;
             reversed += toReverse % 2;
             toReverse /= 2;
     }

     return reversed;
}
Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top