Python GrayCode保存为字符串直接转十进制

Python GrayCode saved as string directly to decimal

我正在为一个 python 项目工作,我想知道以下是否可行:

目前我有一个存储为字符串的格雷码,即:“1000”,我想将其转换为整数(十进制,base10)值 --> 15

下面table表示二进制码值到格雷码值的转换:

Decimal Value Binary Equivalent Gray Code Equivalent Decimal Value of Gray Code Equivalent
0 000 000 0
1 001 001 1
2 010 011 3
3 011 010 2
4 100 110 6
5 101 111 7
6 110 101 5
7 111 100 4

试试这个代码

从十进制到格雷码

def grayCode(n):
     
    # Right Shift the number
    # by 1 taking xor with
    # original number
    return n ^ (n >> 1)
 
 
# Driver Code
n = "1000"
print(grayCode(int(n)))

从格雷码到十进制

def inversegrayCode(n):
    inv = 0;
     
    # Taking xor until
    # n becomes zero
    while(n):
        inv = inv ^ n;
        n = n >> 1;
    return inv;
 
# Driver Code
n = "15";
print(inversegrayCode(int(n)));

来源:geeksforgeeks

来自RosettaCode

def gray_decode(n):
    m = n >> 1
    while m:
        n ^= m
        m >>= 1
    return n

这需要一个 int 作为输入,所以你必须在调用函数之前解析字符串:

a = "1000"
print(gray_decode(int(a, 2)))

有个很好的例子here 要点是:

n = '1000'
n = int(n, 2) # convert to int
 
mask = n
while mask != 0:
    mask >>= 1
    n ^= mask