[Tutor] How can I convert hex string to binary string?
Scot Stevenson
scot@possum.in-berlin.de
Wed, 3 Apr 2002 13:22:09 +0200
Hello Ares,
> such as '0A0B' to '0000101000001011' ?
> is there any function or module?
If I remember my binary math, each hex numeral (0 to F, that is) has an
equivalent four digit binary number (0000 to 1111), so that
Hex - Bin
0 0000
2 0010
3 0011
...
E 1110
F 1111
So all you should have to do is a) make a dictionary with something of the
sort of
convert = {'0': '0000', '1': '0001', '2': '0010', ....}
and b) go thru all letters in the string and string their bin values
together:
This seems to work for me:
========================================
convert = {'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'}
hexstring = '38CF' # our example
binstring = ''
for hexletter in hexstring:
binstring = binstring + convert[hexletter]
print binstring
==========================================
Y, Scot