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 December 2025. Register Now!

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.