Skip to content

Fix float16 pack/unpack on big-endian architectures#55

Merged
eerimoq merged 1 commit intoeerimoq:masterfrom
lemenkov:endianness
Feb 17, 2026
Merged

Fix float16 pack/unpack on big-endian architectures#55
eerimoq merged 1 commit intoeerimoq:masterfrom
lemenkov:endianness

Conversation

@lemenkov
Copy link
Contributor

pack_float_16() and unpack_float_16() pass PY_BIG_ENDIAN as the byte-order parameter to PyFloat_Pack2/PyFloat_Unpack2 (and their underscore-prefixed predecessors).

That parameter is named le (little-endian): 0 means big-endian storage, 1 means little-endian. PY_BIG_ENDIAN expands to 1 on big-endian hosts, which tells the API to use little-endian storage — the opposite of what the bitstream layer expects (MSB-first).

On little-endian hosts PY_BIG_ENDIAN is 0, which accidentally matches the bitstream convention, so the bug is invisible there.

Fix: always pass 0 (big-endian) so the buffer matches the bitstream byte order regardless of host architecture.

This fixes the big-endian test failures reported in #21 (second comment, by @besser82):

FAIL: test_pack — b'\x00<' != b'<\x00'
FAIL: test_unpack — (3.5762786865234375e-06,) != (1.0,)

Note: the first comment in #21 (byte-order suffixes </> being silently ignored by the C extension) is a separate issue and is not addressed here.

PyFloat_Pack2() and PyFloat_Unpack2() (and their underscore-prefixed
predecessors) take an 'le' parameter where 0 means big-endian and 1
means little-endian storage. The code was passing PY_BIG_ENDIAN which
evaluates to 0 on little-endian and 1 on big-endian - exactly the
opposite of what is needed, since the bitstream always operates in
big-endian (MSB-first) byte order.

On little-endian systems PY_BIG_ENDIAN=0 happened to produce the correct
result (big-endian storage), masking the bug. On big-endian systems
PY_BIG_ENDIAN=1 caused little-endian storage, resulting in byte-swapped
float16 values.

Replace PY_BIG_ENDIAN with the literal 0 (= big-endian) to get
consistent behavior across all architectures.

Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
Assisted-by: Claude (Anthropic) <https://claude.ai>
@eerimoq
Copy link
Owner

eerimoq commented Feb 17, 2026

Thanks!

@eerimoq eerimoq merged commit 39be351 into eerimoq:master Feb 17, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants