[Tutor] ASCII hex to binary

Jeff Shannon jeff@ccvcorp.com
Mon Aug 4 17:16:01 EDT 2003


>
>
>>>Can some please tell me how can i express an ASCII hexadecimal string in
>>>the binary form with python.
>>>
>You can also take advantage of the fact that a single hex value (0-F) can
>be represented as a 4-digit binary number. Here's a highly obfuscated
>version, which I wouldn't recommend including anywhere.
>

A rather less-obfuscated version, using a dictionary instead of 
constructing the binary representations on the fly:

binhex = { '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'  }

def hex_to_bin(hexstring):
    inputlist = list(hextring.upper())
    outputlist = [binhex[x] for x in inputlist]
    return "".join(outputlist)

One could perhaps use the inner loop of the obfuscated version to 
construct the binhex dictionary, but I'd be just as happy typing it out 
-- it's much easier to understand what you're doing here when you can 
*see* what the dictionary lookup is returning.

Jeff Shannon
Technician/Programmer
Credit International






More information about the Tutor mailing list