Serializing Signed Integers with an Explicit Width
A binary serializer should choose signedness, width, and byte order together so another reader can recover the same value.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a negative byte
Serializing minus two as one two's-complement byte yields FE in hexadecimal. A matching signed reader yields minus two, while an unsigned reader yields 254. Two's-complement rules describe the difference.
Test with two widths
For a positive value of 258, a two-byte big-endian representation is 01 02. One byte cannot hold it. Combine negative and multibyte cases when testing a round trip.[1]
Check representation and byte order in one round trip
Signed value minus three in sixteen-bit two's complement has pattern 0xFFFD. A big-endian encoding writes FF FD, and little-endian writes FD FF. Decoding either with its corresponding order and signed width reconstructs minus three. See multi-byte order.
Width: 16 bits, range -32768 to 32767
Value -3 → bits 11111111 11111101
Big endian bytes FF FD
Unsigned interpretation of same big-endian bytes: 65533
Reject out-of-range values distinctly from malformed bytes
The integer 32768 cannot round-trip as a signed sixteen-bit value. A one-byte input also fails when a fixed two-byte field is required. Test both boundaries and keep the width and signedness explicit in every interface.