How to Convert Gray Code to Binary in Python


In this example, we will learn how to make a conversion from the Gray code to binary code.

The definition of Gray code can be found in Wikipedia.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def grayToBinary(n):
    """Convert Gray code to binary code"""
    x = int(n, 2)
    y = x
    while x != 0:
        x >>= 1
        y ^= x
    return bin(y)[2:]

n = input("Please input Graya Code: ")
a = grayToBinary(n)
print("The corresponding binary code: ", a)

Output:

Please input Graya Code: 101
The corresponding binary code: 110

Please input Graya Code: 11101
The corresponding binary code: 10110
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments