Convert hexadecimal string to binary

Harry George harry.g.george at boeing.com
Thu Apr 22 12:46:14 EDT 2004


ekoome at yahoo.com (Eric) writes:

> Guys,
> I have the following hexadecimal string - '\xff\xff\xff' which i need
> to convert to binary.
> 
> How would i go about doing this?
> 
> Eric

Assuming you mean the result is a string of "1" and "0" chars, here is
a mechanism.  We use a lookup to avoid converting to and from internal
numbers.

#---x is the data---
x='\xff\xff\xff'
#---notice it is actually a sequence of 8-bit bytes--- 
#---generate a dictionary of all 256 values and their binary codings---
bits={'\x00':'00000000',
      '\x01':'00000001',
      ..........
      '\xff':'11111111'}

#---collect answer in buffer---
s=StringIO.StringIO()
for byte in x:
    s.write(bits[byte])

#---report result---
print s.getvalue()





-- 
harry.g.george at boeing.com
6-6M21 BCA CompArch Design Engineering
Phone: (425) 342-0007



More information about the Python-list mailing list