IEEE 754 floats

Peter Otten __peter__ at
Tue Sep 14 16:07:33 CEST 2004

Dale Huffman wrote:

> Is there a simple way to convert an IEEE-754 floating point ascii
> string ( "0x40400000" = 3.0, 32bit ) into a float variable, without
> writing a function to do the math.  I have transferred this across a
> network from a device I have no contol over and it sends all data as a
> string.  Everything I have tried just converts from hex to decimal and
> adds a decimal point and a zero.
> string.atof("0x40400000")  returns 1077936128.0
> In case I'm not explaining clearly, what I'm looking for could be
> coded in C as follows:
> int     a = 0x40400000;
> float *ap = (float *)&a;
> float myFloat = *ap;
> Sorry if the C offeded anyone in the Py crowd but I'm new to Python
> and so far it rocks - I just don't have the basics down yet.

>>> struct.unpack("f", struct.pack("l", int("0x40400000", 16)))[0]

There may be simpler ways, though.


More information about the Python-list mailing list