【发布时间】:2016-05-05 10:15:17
【问题描述】:
我最近遇到了格雷码,我一直在试图围绕用于将格雷码转换回二进制(32 位或更少)的有效算法陷入困境。
num = num ^ (num >> 16);
num = num ^ (num >> 8);
num = num ^ (num >> 4);
num = num ^ (num >> 2);
num = num ^ (num >> 1);
这就是我所说的代码。现在这是我的问题:
- 这与普通代码有什么区别(右移 1 和 XOR 直到
mask == 0)? - 为什么专门使用 16、8、4、2、1 而不是任何其他小于 32 位的数字?
-
如果我们反过来做有什么区别:
num = num ^ (num >> 1); num = num ^ (num >> 2); num = num ^ (num >> 4); num = num ^ (num >> 8); num = num ^ (num >> 16);我已经试过了,它似乎产生了相同的结果。
【问题讨论】:
-
I have tried [reverse] and it seems to yield the same result.你能证明吗?What is the difference between [shift by powers of 2] and the [basic algorithm] (right shift by 1…)尝试更小的例子。