Python Program to Convert Binary to Gray Code

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

Problem Description

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

Problem Solution

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

Program/Source Code

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

def binary_to_gray(n):
    """Convert Binary to Gray codeword and return it."""
    n = int(n, 2) # convert to int
    n ^= (n >> 1)
 
    # 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 binary number: ')
b = binary_to_gray(g)
print('Gray codeword:', b)
Program Explanation

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

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

Sanfoundry Global Education & Learning Series – 1000 Python Programs.

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

🎓 Free Certifications on 300 subjects are live for January 2026. Register Now!

👉 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