We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e2a78d4 commit 9906186Copy full SHA for 9906186
1 file changed
conversions/Binary_to_gray.py
@@ -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