Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Convert Binary to Gray Code
When it is required to convert binary code to gray code, a method is defined that performs the XOR operation. Gray code is a binary numeral system where two successive values differ in only one bit, making it useful in digital circuits and error correction.
Below is the demonstration of the same ?
Understanding Gray Code Conversion
The conversion from binary to Gray code follows a simple rule:
The most significant bit of Gray code is the same as the binary code
For other bits, the Gray code bit is the XOR of the current binary bit and the previous binary bit
Algorithm Visualization
Example
def binary_to_gray_op(binary_str):
# Convert binary string to integer
n = int(binary_str, 2)
# XOR with right shifted version
n ^= (n >> 1)
# Convert back to binary string (remove '0b' prefix)
return bin(n)[2:]
# Example conversion
binary_input = '101100110'
gray_result = binary_to_gray_op(binary_input)
print(f'Binary input: {binary_input}')
print(f'Gray code output: {gray_result}')
Binary input: 101100110 Gray code output: 111010101
Step-by-Step Manual Conversion
Let's trace through the conversion process manually ?
def manual_binary_to_gray(binary_str):
gray_code = []
# First bit of gray code is same as binary
gray_code.append(binary_str[0])
# Remaining bits are XOR of adjacent binary bits
for i in range(1, len(binary_str)):
# XOR current bit with previous bit
xor_result = str(int(binary_str[i-1]) ^ int(binary_str[i]))
gray_code.append(xor_result)
print(f'Step {i}: {binary_str[i-1]} ? {binary_str[i]} = {xor_result}')
return ''.join(gray_code)
binary_input = '1011'
print(f'Converting binary {binary_input} to Gray code:')
print(f'First bit: {binary_input[0]}')
gray_result = manual_binary_to_gray(binary_input)
print(f'Final Gray code: {gray_result}')
Converting binary 1011 to Gray code: First bit: 1 Step 1: 1 ? 0 = 1 Step 2: 0 ? 1 = 1 Step 3: 1 ? 1 = 0 Final Gray code: 1110
Interactive Example with User Input
def binary_to_gray_op(binary_str):
try:
# Validate binary input
int(binary_str, 2) # This will raise ValueError if not binary
n = int(binary_str, 2)
n ^= (n >> 1)
return bin(n)[2:]
except ValueError:
return "Invalid binary input"
# Get user input
binary_val = input('Enter the binary number: ')
gray_result = binary_to_gray_op(binary_val)
print('Gray code output:', gray_result)
Explanation
A method named
binary_to_gray_opis defined that takes the binary string as parameterThe binary string is converted to an integer using
int(binary_str, 2)The XOR operation
n ^= (n >> 1)performs the Gray code conversion efficientlyThe
>>operator performs a right bit shift, and^performs XORThe result is converted back to binary string using
bin()and formatted by removing the '0b' prefix
Conclusion
Binary to Gray code conversion is efficiently achieved using XOR operations. The algorithm XORs each bit with its previous bit, making it useful for error detection and digital circuit applications.
