Skip to content

struct (un)packing of half-precision may turn NaN into ±inf #141042

@robsdedude

Description

@robsdedude

Bug report

Bug description:

import struct
f = struct.unpack(">d", bytes.fromhex("7FF0000000080001"))[0]
print(f)  # nan

f2 = struct.unpack(">f", struct.pack(">f", f))[0]
print(f2)  # inf

Repeating this with FFF0000000080001 you'll see nan turn into -inf.

This only happens in Python 3.14+ (not 3.13). I'm pretty sure that this fix is causing it: #130317

Preserving the signaling/quieting bit is a great idea, I find. But since the mantissa is being truncated, one must ensure that the narrower width mantissa doesn't end up being all 0 bits as that represents inf instead of nan.

CPython versions tested on:

3.14

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.14bugs and security fixes3.15new features, bugs and security fixesextension-modulesC modules in the Modules dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions