Skip to content

Commit 9b38b9d

Browse files
Add binary to gray code conversion algorithm (#13826)
* Create Binary_to_gray.py * Update and rename Binary_to_gray.py to binary_to_gray.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent f1a8457 commit 9b38b9d

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

‎conversions/binary_to_gray.py‎

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

0 commit comments

Comments
 (0)