位反转
这里的位反转(Bit Reversal),指的是一个数的所有bit位依照中点对换位置,例如0b0101 0111 => 0b1110 1010。也可以叫二进制逆序,按位逆序,位翻转等等。
算法说明
该算法用于将8bit数进行位反转。算法用到了64bit乘法与取模运算。算法通过3次运算完成位反转操作。
位反转算法代码
unsigned char reverse(unsigned char x)
{
x = (x * 0x0202020202ULL & 0x010884422010ULL) % 1023;
return x;
}
算法来源
This method was attributed to Rich Schroeppel in the Programming Hacks section of Beeler, M., Gosper, R. W., and Schroeppel, R. HAKMEM. MIT AI Memo 239, Feb. 29, 1972.
算法计算过程
用abcdefgh表示一个8bit数的8个bit位。
计算分为三个步骤
1.x * 0x0202020202ULL
x乘以0x0202020202ULL。
2.x * 0x0202020202ULL & 0x010884422010ULL
步骤一得到的数值再与0x010884422010ULL。
3.(x * 0x0202020202ULL & 0x010884422010ULL) % 1023
步骤二得到的数值再取模运算1023,1023 =
2
10
−
1
2^{10} - 1
210−1,相当于将每10bit的数合并在一起,从0-9,10-19,20-29,30-39,……。
最后完成从abcdefgh到hgfedcba的位反转操作。
拓展
可以使用该位反转算法实现32位数的位反转。
代码如下:
unsigned char reverse(unsigned char x)
{
x = (x * 0x0202020202ULL & 0x010884422010ULL) % 1023;
return x;
}
unsigned int reverse_32(unsigned int x)
{
x = (reverse(x & 0xff) << 24)|
(reverse(x >> 8 & 0xff) << 16)|
(reverse(x >> 16 & 0xff) << 8)|
(reverse(x >> 24 & 0xff) );
return x;
}
[参考资料]
Bit Twiddling Hacks By Sean Eron Anderson
[Hacker’s Delight] 作者: Henry S. Warren Jr.