struct doesn't handle NaN values?

David M. Cooke cookedm+news at physics.mcmaster.ca
Thu May 13 17:08:41 EDT 2004


At some point, Grant Edwards <grante at visi.com> wrote:

> Perhaps I'm doing something wrong: the struct module docs say
> it's IEE 754, but I can't figure out how to get it to handle
> NaN values correctly (either packing or unpacking).
>
>>>> x = float('nan')
>>>> struct.pack("<f",x)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> SystemError: frexp() result out of range

Doing this with the native format is no trouble:
>>> struct.pack('f', x)
'\x00\x00\xc0\x7f'

...which is a NaN since the exponent part is all 1's and the
significand is non-zero.

>>>> struct.unpack("<f",'\xff\xff\xff\xff')
> (-6.8056469327705772e+38,)

Again,
>>> struct.unpack('f', '\xff\xff\xff\xff')
(nan,)

Of course, if you want to worry about endian issues here, I think
you're SOL with using struct.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list