Skip to content

Commit 9906186

Browse files
authored
Create Binary_to_gray.py
1 parent e2a78d4 commit 9906186

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

conversions/Binary_to_gray.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Function to convert Binary number to Gray code
2+
def binary_to_gray(binary):
3+
# Convert binary (string) to integer
4+
binary = int(binary, 2)
5+
6+
# Perform XOR between binary and binary right-shifted by 1 bit
7+
gray = binary ^ (binary >> 1)
8+
9+
# Convert back to binary string and remove '0b' prefix
10+
gray_code = bin(gray)[2:]
11+
12+
return gray_code
13+
14+
15+
# --- Main Program ---
16+
17+
# Taking input from the user
18+
binary_input = input("Enter a binary number: ")
19+
20+
# Input validation
21+
if not all(bit in '01' for bit in binary_input):
22+
print("❌ Invalid input! Please enter a binary number (0s and 1s only).")
23+
else:
24+
gray_result = binary_to_gray(binary_input)
25+
print(f"✅ The Gray code for binary {binary_input} is: {gray_result}")

0 commit comments

Comments
 (0)