Python Program to convert a binary number to gray code

In this simple python program, we need to convert binary code to gray code. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

What are the gray code and binary numbers?

To solve this python program to convert a binary number to gray code, we need to know a bit about the binary number and gray code.

The binary number is familiar to almost all of us as it is a number system to the base 2. Where our decimal system is to the base 10. Base 2 means there are only zeros and ones to represent a number. For example, consider a number 2 in decimal, which has the binary form 010. The binary number system is used in machine language, which means any programming language will be converted to binary before executing.

How a binary number converted to gray code in python?

The best explanation for the Gray code is it is the reflection of a binary number. It is an ordering of numbers like that two successive numbers differ by only one bit in binary. It is called a reflected binary. Gray code is used in cable tv, digital signal transmission, etc.

Here we need to convert the Binary to Gray code so the logic behind is we are doing an XOR operation between the number in binary and the (number - 1), where the number -1 is calculated by right shifting the bits of the number. Where the number will be greater than zero if the number is zero in binary gray code is also zero.


STEP 1: Accept a binary number from the user using the input method in python programming.

STEP 2: Call the function for converting the binary to gray code.

STEP 3: Print the returned value from the function as gray code using print statement in the python programming language.


STEP 1: Receive the binary number as a parameter and convert that to an integer using int and use the precision of 2.

STEP 2: Do an XOR operation with the number in binary and the number -1, where the number -1 is calculated using the right shift the bit of the number using the right shift operator in python.

STEP 3: Return the value using the bin and use the slice operation to remove the 0b prefix, which comes in the bin method of binary representation.

Python Source Code

                                          def binarytog(n):
    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 = binarytog(g)
print('Gray codeword:', b)


Enter binary number: 110

Gray codeword: 101