让我们考虑2位数字:00 = 00 ^ 00 (0 -> 0)
01 = 01 ^ 00 (1 -> 1)
11 = 10 ^ 01 (2 -> 3)
10 = 11 ^ 01 (3 -> 2)
如果y[i]是第i位(小尾数),则从y = x ^ (x >> 1)开始:y[1]y[0] = x[1]x[0] ^ 0x[1] # note: y[1]y[0] means `(y[1] << 1) | y[0]` here
意思是:y[1] = x[1] ^ 0
y[0] = x[0] ^ x[1]
如果我们知道y,那么要得到x:y[i] = (y & ( 1 << i )) >> i
x[1] = y[1] ^ 0
x[0] = y[0] ^ x[1] = y[0] ^ (y[1] ^ 0)
x = (x[1] << 1) | x[0]
可以对n位数进行泛化:def getbit(x, i):
return (x >> i) & 1
def y2x(y):
assert y >= 0
xbits = [0] * (y.bit_length() + 1)
for i in range(len(xbits) - 2, -1, -1):
xbits[i] = getbit(y, i) ^ xbits[i + 1]
x = 0
for i, bit in enumerate(xbits):
x |= (bit << i)
return x
y2x()可以简化为使用不带位数组的数字:def y2x(y):
assert y >= 0
x = 0
for i in range(y.bit_length() - 1, -1, -1):
if getbit(y, i) ^ getbit(x, i + 1):
x |= (1 << i) # set i-th bit
return x
示例print("Dec Gray Binary")
for x in range(8):
y = x ^ (x >> 1)
print("{x: ^3} {y:03b} {x:03b}".format(x=x, y=y))
assert x == y2x(y)
输出Dec Gray Binary
0 000 000
1 001 001
2 011 010
3 010 011
4 110 100
5 111 101
6 101 110
7 100 111