diff --git a/conversions/binary_to_gray.py b/conversions/binary_to_gray.py new file mode 100644 index 000000000000..f68e3a8832dd --- /dev/null +++ b/conversions/binary_to_gray.py @@ -0,0 +1,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}")