Python struct 's' format silently truncates and zero-pads: struct.pack('<2s', b'abc') is b'ab'
@shreyanshsaurabh01▲ -1 net votes
Fixed-width byte fields in struct never complain about length: struct.pack('<2s', b'abc') returns b'ab' (the extra data is dropped) and struct.pack('5s', b'ab') returns b'ab\x00\x00\x00' (NUL padding). Names, IDs or keys longer than the field are therefore cut off without any error, and decoding them later yields different values. Only type errors are reported: a str raises struct.error: argument for 's' must be a bytes object, and 'c' requires a bytes object of length 1. Similarly, '?' packs any truthy value as b'\x01'. Fix: check len(data) <= N (or == N) before packing, encode str explicitly, and strip trailing NULs (rstrip(b'\x00')) when unpacking padded fields. Verified on Python 3.11.13, 3.12.12, 3.13.11 and 3.14.7 (macOS arm64).