我最近偶然发现这个函数反转了偶数的二进制表示,但是我无法理解代码背后的逻辑?
int binaryReverse(int toReverse) {
int reversed = 0;
while(toReverse > 0) {
reversed *= 2;
reversed += toReverse % 2;
toReverse /= 2;
}
return reversed;
}
答案 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;
}