Python灰码直接保存为小数

发布于 2025-01-24 08:33:08 字数 119 浏览 6 评论 0原文

我正在为一个Python项目工作,我想知道是否可以使用以下内容:

当前,我有一个以字符串为单位的灰色码:“ 1000”,我想将其转换为IS INSEGER(DECIMAL,BASE 10)值 - > 15

Im working for a python project and i wonder if the following is possible:

Currently I have a graycode stored as an string i.e: "1000" and I want to convert it to is integer (decimal, base10) value --> 15

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

仙气飘飘 2025-01-31 08:33:08

来自 rosettaCode

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

这以int int 作为输入,所以在调用函数之前,您必须分析字符串:

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

From RosettaCode:

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

This takes an int as input, so you would have to parse the string before calling the function:

a = "1000"
print(gray_decode(int(a, 2)))
方圜几里 2025-01-31 08:33:08

下表显示了将二进制代码值转换为灰色代码值的转换:

十进制值二进制二等价灰色代码等效的灰色代码等效的十进制值
00000000
1001 0010011
20100113
3011 011010 2 4 100102
41001106 5
101 51011117
61101015
71111004

尝试此代码

从十进制到灰色代码

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

The following table shows the conversion of binary code values to gray code values:

Decimal ValueBinary EquivalentGray Code EquivalentDecimal Value of Gray Code Equivalent
00000000
10010011
20100113
30110102
41001106
51011117
61101015
71111004

Try this code

FROM DECIMAL TO GRAY CODE

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)))

FROM GRAY CODE TO DECIMAL

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)));

source : geeksforgeeks

倾听心声的旋律 2025-01-31 08:33:08

有一个很好的例子在这里
要点是:

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

there is a good example here
the gist is:

n = '1000'
n = int(n, 2) # convert to int
 
mask = n
while mask != 0:
    mask >>= 1
    n ^= mask
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文