Python Program to Convert Gray to Binary Code

In this Python program, we will convert Gray codes to binary codes. Gray code is a binary numeral system where two successive values differ by only one bit. Converting Gray codes to binary codes allows us to obtain the corresponding binary representation.

Problem Statement

Given a Gray code as input, we need to convert it to its equivalent binary code.

Python Program to Convert Gray to Binary Code

def gray_to_binary(gray_code):
    binary_code = gray_code[0]
    
    for i in range(1, len(gray_code)):
        if gray_code[i] == '0':
            binary_code += binary_code[i-1]
        else:
            binary_code += str(1 - int(binary_code[i-1]))
    
    return binary_code


# Test the program
gray_code = input("Enter the Gray code: ")
binary_code = gray_to_binary(gray_code)

print(f"Binary code: {binary_code}")

How It Works

  1. The function gray_to_binary(gray_code) takes a Gray code as input and returns its equivalent binary code.
  2. We initialize binary_code as the first character of the Gray code, as it remains unchanged during conversion.
  3. Starting from the second character of the Gray code, we iterate through each bit.
  4. If the current bit is ‘0’, we append the same value as the previous bit of binary_code to binary_code.
  5. If the current bit is ‘1’, we append the complement of the previous bit of binary_code to binary_code (1 minus the previous bit value).
  6. After iterating through all the bits of the Gray code, we have the complete binary code.
  7. Finally, we return binary_code, which will be the equivalent binary code of the input Gray code.

Input/Output

Python Program to Convert Gray to Binary Code

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...