0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

通常の2進数とGray Codeの相互変換

0
Posted at

はじめに

本記事では、2進数との変換方法と、次のグレイコードを求める方法を Python で簡潔に紹介します。

通常の2進数からGray Codeへの変換

「元の数」と「1ビット右シフトした数」の XOR をとるだけで求められます。

def binary_to_gray(binary: int) -> int:
    return binary ^ (binary >> 1)

実行例

for b in [0, 1, 2, 3, 7]:
    print(f"{b:03b} -> {binary_to_gray(b):03b}")

# 出力例
# 000 -> 000
# 001 -> 001
# 010 -> 011
# 011 -> 010
# 111 -> 100

Gray Codeから通常の2進数への変換

Gray Code の最上位ビットをそのまま使い、以降のビットは逐次 XOR して求めます。

def gray_to_binary(gray: int) -> int:
    binary = gray
    while gray > 0:
        gray >>= 1
        binary ^= gray
    return binary

実行例

for g in [0, 1, 3, 2, 4]:
    print(f"{g:03b} -> {gray_to_binary(g):03b}")

# 出力例
# 000 -> 000
# 001 -> 001
# 011 -> 010
# 010 -> 011
# 100 -> 111

参考:次のグレイコードを求める

グレイコード → 2進数 → +1 → グレイコード
という手順で求めます。

def next_gray(gray: int) -> int:
    return binary_to_gray(gray_to_binary(gray) + 1)

実行例

for g in [0, 1, 3, 2]:
    print(f"{g:03b} -> {next_gray(g):03b}")

# 出力例
# 000 -> 001
# 001 -> 011
# 011 -> 010
# 010 -> 110

環境情報

  • Python 3.11.13
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?