This is a Python program to convert Gray code to binary.
We are given a Gray codeword. We have to find the associated binary number.
1. The function gray_to_binary is defined.
2. It takes the Gray codeword string as argument.
3. It returns its associated binary number as a string.
4. If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in its associated binary number where the 0th bit is the MSB, it can be shown g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for i > 0.
5. From the above, it follows that b(i) = g(i) XOR g(i – 1) XOR … XOR g(0).
6. Thus a Gray codeword g can be converted to its associated binary number by performing (g XOR (g >> 1) XOR (g >> 2) XOR … XOR (g >> m)) where m is such that g >> (m + 1) equals 0.
Here is the source code of a Python program to convert Gray code to binary. The program output is shown below.
def gray_to_binary(n): """Convert Gray codeword to binary and return it.""" n = int(n, 2) # convert to int mask = n while mask != 0: mask >>= 1 n ^= mask # 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 Gray codeword: ') b = gray_to_binary(g) print('In binary:', b)
1. The user is prompted to enter the Gray codeword.
2. gray_to_binary is called on the Gray codeword.
3. The returned string which is its associated binary number is displayed.
Case 1: Enter Gray codeword: 111 In binary: 101 Case 2: Enter Gray codeword: 1101 In binary: 1001 Case 3: Enter Gray codeword: 10 In binary: 11
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.