Python Program to convert a binary number to gray code


August 4, 2021, Learn eTutorial
702

What are gray codes and binary?

The binary 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 the integer 2 in decimal, which has the binary form 010. it is used in machine language, which means any programming language will be converted to binary before executing.

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.

How do we convert a binary number to gray code in python?

To convert a binary number to gray code in python, we need to do 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.

Note: The integer will be greater than zero, if the number is zero, the gray code is also zero.

ALGORITHM

STEP 1: Accept input from the user.

STEP 2: Call the function for convert to gray code.

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

USER DEFINED FUNCTION binarytog(n)

STEP 1: Receive the user input 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 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.


To convert a binary number to gray code using a python program, we have to use the below concepts, we recommend learning those for a better understanding

Python Source Code

                                          def binarytog(n):
    n = int(n, 2)           # convert to int
    n ^= (n >> 1)
    return bin(n)[2:]     # the slice operation is to remove the prefix as the bin will return with '0b' prefix
 
 
g = input('Enter binary number: ')
b = binarytog(g)
print('Gray codeword:', b)
                                      

OUTPUT

Enter binary number: 110

Gray codeword: 101