Python Program to Convert Gray to Binary Code

This is a Python program to convert Gray code to binary.

Problem Description

We are given a Gray codeword. We have to find the associated binary number.

Problem Solution

1. The function gray_to_binary is defined.
2. It takes the Gray codeword string as argument.
3. It returns its associated binary number as a string.
4. If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in its associated binary number where the 0th bit is the MSB, it can be shown g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for i > 0.
5. From the above, it follows that b(i) = g(i) XOR g(i – 1) XOR … XOR g(0).
6. Thus a Gray codeword g can be converted to its associated binary number by performing (g XOR (g >> 1) XOR (g >> 2) XOR … XOR (g >> m)) where m is such that g >> (m + 1) equals 0.

Program/Source Code

Here is the source code of a Python program to convert Gray code to binary. The program output is shown below.

def gray_to_binary(n):
    """Convert Gray codeword to binary and return it."""
    n = int(n, 2) # convert to int
 
    mask = n
    while mask != 0:
        mask >>= 1
        n ^= mask
 
    # bin(n) returns n's binary representation with a '0b' prefixed
    # the slice operation is to remove the prefix
    return bin(n)[2:]
 
 
g = input('Enter Gray codeword: ')
b = gray_to_binary(g)
print('In binary:', b)
Program Explanation

1. The user is prompted to enter the Gray codeword.
2. gray_to_binary is called on the Gray codeword.
3. The returned string which is its associated binary number is displayed.

advertisement
Runtime Test Cases
Case 1:
Enter Gray codeword: 111
In binary: 101
 
Case 2:
Enter Gray codeword: 1101
In binary: 1001
 
Case 3:
Enter Gray codeword: 10
In binary: 11

Sanfoundry Global Education & Learning Series – 1000 Python Programs.

If you wish to look at all Python Programming examples, go to 1000 Python Programs.

👉 Join Sanfoundry classes at Telegram or Youtube

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels

advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations