Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Binary 理解倒装偶数二进制表示的函数_Binary_Inversion - Fatal编程技术网

Binary 理解倒装偶数二进制表示的函数

Binary 理解倒装偶数二进制表示的函数,binary,inversion,Binary,Inversion,我最近偶然发现了这个函数,它可以反转偶数的二进制表示形式,但我无法理解代码背后的逻辑 int binaryReverse(int toReverse) { int reversed = 0; while(toReverse > 0) { reversed *= 2; reversed += toReverse % 2; toReverse /= 2; } return

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

int binaryReverse(int toReverse) {

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

     return reversed;
}

首先,它不会反转位,而是反转位(并且只反转设置为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;
}
第三,这里有一个更具可读性的版本(尽管它必须将输入作为
无符号的
):

int-binaryReverse(无符号int-torreverse)
{
int=0;
而(反向>0)
{
反转=1;//将输入向右移动一位
}
反向返回;
}

它也适用于奇数。非常感谢,很抱歉用错了词。我是这个网站的不速之客
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;
}