[Tutor] How can I convert hex string to binary string?
Kirby Urner
urnerk@qwest.net
Wed, 3 Apr 2002 00:46:14 -0500
On Wednesday 03 April 2002 03:17 am, Ares Liu wrote:
> def hex2bin(str):
> bin = ['0000','0001','0010','0011',
> '0100','0101','0110','0111',
> '1000','1001','1010','1011',
> '1100','1101','1110','1111']
> aa = ''
> for i in range(len(str)):
> aa += bin[atoi(str[i],base=16)]
> return aa
Good one. Use of list index to access pre-computed strings, vs.
actually computing base 2 values over and over, seems a good
idea.
Slightly simpler (style point: best to not use str as a variable name,
as it's also a built-in function):
#
# hex2bin
#
def hex2bin(hexno):
bin = ['0000','0001','0010','0011',
'0100','0101','0110','0111',
'1000','1001','1010','1011',
'1100','1101','1110','1111']
base2 = ''
for d in hexno:
base2 += bin[int(d,base=16)]
return base2
Kirby