mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-09-28 13:33:11 +08:00
* 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>
51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
"""
|
|
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}")
|