interpret 4 byte as 32-bit float (IEEE-754)

Grant Edwards grante at
Sat Jan 15 13:08:54 EST 2005

On 2005-01-15, Scott David Daniels <Scott.Daniels at Acm.Org> wrote:

>> I've read some bytes from a file and just now I can't interpret 4 bytes 
>> in this dates like a real value.

> OK, here's the skinny (I used blocks & views to get the answer):
> import struct
> bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split())
> struct.unpack('>f', bytes)

Just be careful.  That doesn't work for all 32-bit IEEE floating
point values:

  >>> import struct
  >>> bytes = '\xff\xff\xff\xff'
  >>> print struct.unpack('>f',bytes)

0xffffff is _not_ -6.8...e38.  It's a NaN.

IIRC, it doesn't work for infinities either.  I haven't tried

Grant Edwards                   grante             Yow!  It's hard being
                                  at               an ARTIST!!

More information about the Python-list mailing list