Skip to the content.

Binary Numbers and Logic Gates

Binary Numbers and Logic Gates Teach Teach Blog

Homework Code

TXT File:

0000 0 0001 1 0010 2 0011 3 0100 4 0101 5 0110 6 0111 7 1000 8 1001 9 1010 A 1011 B 1100 C 1101 D 1110 E 1111 F

def load_conversion_table(file_path):
    conversion = {}
    with open(file_path, 'r') as f:
        for line in f:
            binary, hex_digit = line.strip().split()
            conversion[binary] = hex_digit
    return conversion

def binary_to_hex(binary_str, conversion_table):
    while len(binary_str) % 4 != 0:
        binary_str = '0' + binary_str

    hex_str = ''
    for i in range(0, len(binary_str), 4):
        nibble = binary_str[i:i+4]
        hex_digit = conversion_table.get(nibble, '?')
        hex_str += hex_digit
    return hex_str

def main():
    conversion_table = load_conversion_table('conversion.txt')
    binary_input = input("Enter a binary number: ").strip()
    hex_output = binary_to_hex(binary_input, conversion_table)
    print(f"Hexadecimal equivalent: {hex_output}")

main()