Python Program to Convert Binary to Gray Code

PythonServer Side ProgrammingProgramming

When it is required to convert binary code to gray code, a method is defined that performs the ‘xor’ operation.

Below is the demonstration of the same −

Example

 Live Demo

def binary_to_gray_op(n):
   n = int(n, 2)
   n ^= (n >> 1)

   return bin(n)[2:]

gray_val = input('Enter the binary number: ')
binary_val = binary_to_gray_op(gray_val)
print('Gray codeword is :', binary_val)

Output

Enter the binary number: 101100110
Gray codeword is : 111010101

Explanation

  • A method named ‘binary_to_gray_op’ is defined, that takes the binary number as its parameter.

  • It performs the ‘xor’ operation.

  • It returns the converted output.

  • The input of binary number is taken from the user.

  • The function is called, and this value is passed as a parameter to it.

  • The converted output is displayed on the console.

raja
Published on 19-Apr-2021 10:45:19
Advertisements