理解反转偶数二进制表示的函数

时间:2014-03-11 19:49:07

标签: binary inversion

我最近偶然发现这个函数反转了偶数的二进制表示,但是我无法理解代码背后的逻辑?

int binaryReverse(int toReverse) {

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

     return reversed;
}

1 个答案:

答案 0 :(得分:0)

首先,它不会反转这些位,反转它们(并且只有最右边的位和最左边的位之间的位置设置为1)

其次,这是它的工作原理:

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;
}

第三,这是一个可能更易读的版本(虽然它必须将输入作为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;
}