我正在尝试理解格雷码的工作原理。如果我们给出任何非负整数n(其中n是位数),那么我们需要打印它的格雷码序列。以下是一些例子
2位格雷码序列
Input = 2 bits
00 - 0
01 - 1
11 - 3
10 - 2
Output = [0,1,3,2]
3位格雷码序列
Input = 3
000 0
001 1
011 3
010 2
110 6
111 7
101 5
100 4
Output = [0, 1, 3, 2, 6, 7, 5, 4]
根据我的理解,格雷码序列以0开始,而在格雷码中,两个连续值仅在一位上不同。我不确定2的格雷码如何[0,1,3,2]
以及3的格雷码如何来[0,1,3,2,6,7,5,4]
答案 0 :(得分:0)
为n位生成格雷码的通常方法是将n-1位的序列作为前缀0,然后是n-1位的反序列,前缀为1. 1位的基本情况序列为0, 1.您可以轻松编写生成此序列的递归函数:
void printgrey(int len, int pfx=0, int rev=0) {
if (--len >= 0) {
printgrey(len, pfx + (rev<<len), 0);
printgrey(len, pfx + (!rev<<len), 1);
} else
printf("%d\n", pfx);
}
答案 1 :(得分:0)
In hardware the gray encoding is described as follows:
function bin2gray(value : std_logic_vector) return std_logic_vector is
variable result : std_logic_vector(value'range);
begin
result(result'left) := value(value'left);
for i in (result'left - 1) downto result'right loop
result(i) := value(i) xor value(i + 1);
end loop;
return result;
end function;
Source: PoC.utils
What does it mean? The highest bit (MSB) from input is copied to the result. Now, a loop traverses every input bit from MSB-1 to LSB and xors this bit with it's left neighbor.
Example:
in = 0x2 = 0010b
res(3) := 0
res(2) := in(3) xor in(2) = 0
res(1) := in(2) xor in(1) = 1
res(0) := in(1) xor in(0) = 1
return 0011
答案 2 :(得分:0)
生成格雷码序列最简单的方法是从一个正常的数字序列开始,将每个数字与自己右移一位进行异或。在 Python 中它看起来像这样:
def graycodes(bits):
return [x ^ (x >> 1) for x in range(1 << bits)]
>>> graycodes(2)
[0, 1, 3, 2]
>>> graycodes(3)
[0, 1, 3, 2, 6, 7, 5, 4]
>>> graycodes(4)
[0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8]