How to Convert Binary to Gray Code in Python


In this example we will show how to make a conversion from binary code into the Gray code in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def binaryToGray(n):
    """Convert Binary to Gray codeword and return it."""
    # convert to int
    a = int(n, 2)

    # bin(n) returns n's binary representation with a '0b' prefixed
    # the slice operation is to remove the prefix
    return bin(a ^ (a >> 1))[2:]

n = input("Input the binary: ")
a = binaryToGray(n)
print("The corresponding Gray code: ", a)

Output:

Input the binary: 1101
The corresponding Gray code: 1011

Input the binary: 10101
The corresponding Gray code: 11111
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments