Skip to content
Advertisement

hexToBinary dictionary

So I am working on this problem: Recall from the Number Systems unit the method for converting hexadecimal numbers to binary by converting each hex digit to its equivalent four binary digits. Write a Python function named hexToBinary with parameters (number, table) that uses this algorithm to convert a hexadecimal number to a (return) binary number. The algorithm visits each digit in the hexadecimal number, selecting from table the corresponding four bits that represent that digit in binary and then adds these bits to the result string.

This is the code I have written, but I’m not getting it able to work properly:

def hexToBinary (hex, table):
    hexToBinary= {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
    final_hexToBinary = ''
    for hex in hexToBinary:
        final_hexToBinary+=hex
        print(final_hexToBinary)

I am wondering what is wrong with the function, I have a feeling it is a simple mistake.

Advertisement

Answer

def hexToBinary (hex, table):

    final_hexToBinary = ''
    for each  in hex:
        final_hexToBinary+=table[each]
    print(final_hexToBinary)
hexToBinaryTable = {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
hexToBinary("3FB",hexToBinaryTable)

As mentioned it comment your might want to look up the dictionary. If you need not implement the function go for the one mentioned by john galt in comment.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement