-
-
Notifications
You must be signed in to change notification settings - Fork 50.8k
Expand file tree
/
Copy pathbinary_to_gray.py
More file actions
50 lines (36 loc) · 1.37 KB
/
Copy pathbinary_to_gray.py
File metadata and controls
50 lines (36 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
Binary to Gray code conversion algorithm.
Reference:
https://en.wikipedia.org/wiki/Gray_code
"""
def binary_to_gray(binary: str) -> str:
"""
Convert a binary number (as string) to its equivalent Gray code.
The Gray code is generated by XOR-ing each bit with the bit just before it.
Args:
binary (str): A string representing a binary number (e.g., "10101010").
Returns:
str: The corresponding Gray code string.
Example:
>>> binary_to_gray("10101010")
'11111111'
>>> binary_to_gray("1101")
'1011'
"""
# Convert binary string to integer
binary_int = int(binary, 2)
# XOR the binary number with itself shifted right by 1 bit
gray_int = binary_int ^ (binary_int >> 1)
# Convert the integer result back to a binary string (remove '0b' prefix)
gray_code = bin(gray_int)[2:]
# Pad with leading zeros to maintain same bit length as input
return gray_code.zfill(len(binary))
if __name__ == "__main__":
# Take input from user
binary_input = input("Enter a binary number: ").strip()
# Validate the input (only 0s and 1s allowed)
if not all(bit in "01" for bit in binary_input):
print("❌ Invalid input! Please enter only 0s and 1s.")
else:
result = binary_to_gray(binary_input)
print(f"✅ The Gray code for binary {binary_input} is: {result}")