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

說明

  • 定義一個名為“flip_num”的方法來檢查數字是否是 0。

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

  • 定義另一個名為“gray_to_binary”的方法,它將格雷碼作為引數。

  • 它遍歷格雷碼中的數字,並將值儲存在二進位制數的索引中。

  • 如果數字不為 0,則呼叫“flip_num”方法,並將該數字更改為 1。

  • 定義一個二進位制數,然後透過傳遞此值來呼叫該方法。

  • 輸出顯示在控制檯中。

更新於: 2021 年 4 月 19 日

1K+ 瀏覽次數

助力您的 事業

完成課程,獲得認證

開始
廣告