Python Program to convert gray code to binary


January 8, 2023, Learn eTutorial
1131

To understand this python program, we need to know about binary and gray code.

What are gray code and binary code?

Binary code: Binary is a number to the base of 2, which means the number is represented by only zeros and ones. It is used in Machine language. For example, the Binary code for 4 is 0100.

Gray code: Gray code is also known as reflected binary code, which is just an arrangement of the binary numbers like successive values that differ only by 1 bit. An example of a gray code of 4 is 0110.

How to convert gray code to binary in python?

This conversion is achieved by continuous xor operation of an integer and the integer less than one. Again xor with that integer less than 1.

To get the number less than 1, we are using the right shift of the binary and doing the xor operation with the number and the right-shifted number, which is number - 1. So we can say that the gray code can be converted to binary using (g XOR (g >> 1) XOR (g >> 2) XOR … XOR (g >> m)).

ALGORITHM

STEP 1: Enter the gray code from the user side

STEP 2: call the user-defined function graytob(n), passing the number as a parameter.

STEP 3: Print the returned value.

User-defined function graytob(n)

STEP 1: Accept the gray code from the main program.

STEP 2: Convert the gray code to an integer using int in the python programming language.

STEP 3: Store the number in another variable.

STEP 4: Open a while loop until the number.

STEP 5: Right shift the number by one to get the number -1, which is used to xor with the number.

STEP 6: Now, do a xor operation with the number and the right-shifted number until all the while loop iterations.

STEP 7: Return the number in binary representation using bin.


For converting the gray to binary code we used the below concepts in python, we recommend referring those for a better understanding

Python Source Code

                                          def graytob(n):
  
    n = int(n, 2) # convert to int
 
    mask = n
    while mask != 0:
        mask >>= 1
        n ^= mask
 
    return bin(n)[2:]
 
 
g = input('Enter Gray codeword: ')
b = graytob(g)
print('In binary:', b)
                                      

OUTPUT

Enter Gray codeword: 10
In binary: 11