I want to convert Gray code to binary in python and c

107 Views Asked by At

In two languages C and python3 I need to know How can i convert Gray code to its equal in binary?

For example 0111 in Gray code is equal to 0101 in binary.

Grey->Binary
0000->0000
0001->0001
0011->0010
0010->0011
0110->0100
0111->0101
1

There are 1 best solutions below

0
NULL On

Python code to convert grey code to binary:

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 = "1000"
print(f"Binary code of: {gray_code} is {gray_to_binary(gray_code)}")

And as far as C, I have no experience so the best I can do is provide a link to some code that seems to work. includehelp.com/c-programs