In this simple python program, we need to convert gray code to binary. 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:
This python program example is for converting the gray code to binary. To understand this program, we need to know what is a Binary and gray code.
Binary code: Binary is a number code 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 1 is 001.
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 1 is 001.
In this python program, we need to convert the gray code to binary, which can be achieved by continuous xor operation of the number and the number less than one. Again xor with that number 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)).
STEP 1: Enter the gray code from the user side using the
input function in the python programming language.
STEP 2: call the user-defined function graytob(n) to convert the gray code to binary code, passing the number as a parameter.
STEP 3: Print the binary number which is returned from the user-defined function using
STEP 1: Accept the binary number from the main program.
STEP 2: Convert the binary number to an integer using
int in the python programming language.
STEP 3: Store the number into 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 in python.
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)
Enter Gray codeword: 10 In binary: 11