Steven D'Aprano <steve+pyt...@pearwood.info> added the comment:

This is not a bug, and I'm unconvinced that it needs a documentation change. If 
you are using struct to assemble values, you need to know the meaning of the 
struct format.

It returns a float NAN because you give it the bit pattern of a NAN.

For C singles and doubles, some bit patterns give numbers, two give signed 
zeroes, two give signed INFs (infinities), and some give NANs. If your bit 
pattern happens to be a NAN, you will get a NAN.

That is no more special or unexpected than this:

>>> struct.unpack('>f', struct.pack('HH', 65, 7392))
(8.05471420288086,)
>>> struct.unpack('<f', struct.pack('HH', 65, 7392))
(1.482314221017757e-21,)

If you reverse the bit pattern by changing the endianism, you get a different 
number.

You already know how to avoid this: if your bit pattern is littlendian, don't 
pack it into a bigendian struct, and vice versa.

To convert it, you would have to pack the float back into a bit array, reverse 
the bits, then unpack it. But it's much easier to just get the endianism right 
in the first place.

It's not the sign bit. Its the whole bit pattern. If it happens to match the 
bit pattern of a NAN when you reverse it, you get a NAN.

The format of singles are described here:

https://en.wikipedia.org/wiki/Single-precision_floating-point_format

----------
nosy: +steven.daprano
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue45032>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to