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