Python Program to Convert Binary to Gray Code

In this Python program, we will convert a binary number to its corresponding Gray code. The Gray code is a binary numeral system where two consecutive values differ by only one bit position. It finds applications in various fields, such as error detection and digital communications.

Problem Statement

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

Python Program to Convert Binary to Gray Code

def binary_to_gray(binary):
    gray = binary[0]  # The first bit of Gray code remains the same as the binary number
    for i in range(1, len(binary)):
        # XOR operation between consecutive bits of binary number
        gray += str(int(binary[i]) ^ int(binary[i - 1]))
    return gray


# Main program
binary_number = input("Enter a binary number: ")
gray_code = binary_to_gray(binary_number)
print("Gray code:", gray_code)

       

How It Works

  1. The binary_to_gray() function takes a binary number as input and returns its corresponding Gray code representation.
  2. The first bit of the Gray code remains the same as the first bit of the binary number.
  3. For each subsequent bit in the binary number, we perform an XOR operation between the current bit and the previous bit in the binary number. The result of the XOR operation gives us the corresponding bit in the Gray code.
  4. We iterate through the binary number starting from the second bit (i = 1) and append the XOR result to the Gray code string.
  5. Finally, we return the Gray code representation of the binary number.
  6. In the main program, we prompt the user to enter a binary number.
  7. We pass the binary number to the binary_to_gray() function to convert it to Gray code.
  8. The resulting Gray code is then printed as output.

Input/Output

Python Program to Convert Binary to Gray Code

Leave A Reply

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

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...