IEEE 754 floats

Robert Kern rkern at ucsd.edu
Tue Sep 14 16:16:06 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.

Take a look at the struct module.

E.g.

In [6]: import struct

In [7]: s = struct.pack('i', 0x40400000)

In [8]: s
Out[8]: '@@\x00\x00'

In [9]: struct.unpack('f', s)
Out[9]: (3.0,)

You might have to worry about endian-related issues, of course, but the 
struct module allows you to handle the various cases.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter



More information about the Python-list mailing list