Python 程序将格雷码转换为二进制码


当需要将格雷码转换为二进制码时,可以定义一种方法来检查数字是否是 0。

以下是对相同方法的演示 −

示例

 实时演示

def flip_num(my_nu):
   return '1' if(my_nu == '0') else '0';

def gray_to_binary(gray):
   binary_code = ""
   binary_code += gray[0]
   for i in range(1, len(gray)):

      if (gray[i] == '0'):
         binary_code += binary_code[i - 1]
      else:
         binary_code += flip_num(binary_code[i - 1])

   return binary_code
gray_code = "01101001"
print("The gray code is :")
print(gray_code)
print("Binary code of", gray_code, "is", gray_to_binary(gray_code))

输出

The gray code is :
01101001
Binary code of 01101001 is 01001110

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义一个名为“flip_num”的方法来检查数字是否是 0。

  • 如果是 0,则返回 1,否则返回 0。

  • 定义另一个名为“gray_to_binary”的方法,它将格雷码作为参数。

  • 它遍历格雷码中的数字,并将值存储在二进制数的索引中。

  • 如果数字不为 0,则调用“flip_num”方法,并将该数字更改为 1。

  • 定义一个二进制数,然后通过传递此值来调用该方法。

  • 输出显示在控制台中。

更新于: 2021 年 4 月 19 日

1K+ 浏览次数

助力您的 事业

完成课程,获得认证

开始
广告