Python Program to Convert Gray Code to Binary

PythonServer Side ProgrammingProgramming

When it is required to convert gray code to binary code, a method is defined, that checks to see if the number is 0 or not.

Below is the demonstration of the same −

Example

 Live Demo

def flip_num(my_nu):
   return '1' if(my_nu == '0') else '0';

def gray_to_binary(gray):
   binary_code = ""
   binary_code += gray[0]
   for i in range(1, len(gray)):

      if (gray[i] == '0'):
         binary_code += binary_code[i - 1]
      else:
         binary_code += flip_num(binary_code[i - 1])

   return binary_code
gray_code = "01101001"
print("The gray code is :")
print(gray_code)
print("Binary code of", gray_code, "is", gray_to_binary(gray_code))

Output

The gray code is :
01101001
Binary code of 01101001 is 01001110

Explanation

  • A method named ‘flip_num’ is defined that checks to see if the number is 0.

  • If it is 0, it returns 1, else it returns 0.

  • Another method named ‘gray_to_binary’ is defined that takes a gray code as a parameter.

  • It iterates over the numbers in gray code, and stores the value in binary number’s index.

  • If the number is not 0, then the ‘flip_num’ method is called, and the number is changed to 1.

  • A binary number is defined, and the method is called by passing this value.

  • The output is displayed on the console.

raja
Published on 19-Apr-2021 10:44:35
Advertisements