This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients jrojas, steven.daprano
Date 2021-08-28.00:39:42
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1630111182.43.0.444781853816.issue45032@roundup.psfhosted.org>
In-reply-to
Content
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
History
Date User Action Args
2021-08-28 00:39:42steven.dapranosetrecipients: + steven.daprano, jrojas
2021-08-28 00:39:42steven.dapranosetmessageid: <1630111182.43.0.444781853816.issue45032@roundup.psfhosted.org>
2021-08-28 00:39:42steven.dapranolinkissue45032 messages
2021-08-28 00:39:42steven.dapranocreate