[Tutor] How can I convert hex string to binary string?

Ares Liu Ares.liu@Clarent.com
Wed, 3 Apr 2002 16:17:48 +0800


Thank you very much.

I've got it.
#
# hex2bin
#
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
# End
>>>hex2bin('0a0b')
'0000101000001011'
#
Regards

Ares
----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Ares Liu" <Ares.liu@Clarent.com>
Cc: <tutor@python.org>
Sent: Wednesday, April 03, 2002 3:44 PM
Subject: Re: [Tutor] How can I convert hex string to binary string?


>
>
> On Wed, 3 Apr 2002, Ares Liu wrote:
>
> > such as '0A0B' to '0000101000001011' ?
> > is there any function or module?
>
> Not directly.  There is a function called int() that can convert something
> like the string '0A0B' into an integer:
>
> ###
> >>> int('0A0B', 16)
> 2571
> ###
>
> So your problem can be simplified to figuring out how to convert a regular
> integer into a binary string.
>
>
> If you have more questions, please feel free to bring them up to Tutor.
> Good luck!