# Convert hexadecimal string to binary

Bengt Richter bokr at oz.net
Thu Apr 22 20:42:58 CEST 2004

```On 22 Apr 2004 08:06:26 -0700, ekoome at yahoo.com (Eric) wrote:

>Guys,
>I have the following hexadecimal string - '\xff\xff\xff' which i need
>to convert to binary.
>
>How would i go about doing this?
>
Assuming that string is the representation of a string of bytes whose binary
values are 255 (or hex 0xff), and you want to view it like a big-endian
number representation, and convert it to an integer (or long, if it gets big),

>>> def s2i(s): return sum([ord(c)*256**i for i,c in enumerate(s[::-1])])
...
>>> s2i('\xff\xff\xff')
16777215
>>> hex(s2i('\xff\xff\xff'))
'0xffffff'
>>> hex(s2i('\x01\x02\x03'))
'0x10203'
>>> hex(s2i('\x01\x02\x03\x04'))
'0x1020304'
>>> hex(s2i('\x01\x02\x03\x04\x05'))
'0x102030405L'
>>> hex(s2i('\x01\x02'))
'0x102'
>>> s2i('\x01\x02')
258

Note that this is unsigned --

>>> hex(s2i('\xff\xff\xff\xff'))
'0xFFFFFFFFL'
>>> hex(s2i('\x80\x00\x00\x00'))
'0x80000000L'

You could do it other and faster ways...

Regards,
Bengt Richter

```