Reading an Unsigned Length Field
A binary reader must know a length field's width, byte order, and unit before using it to take the next part of a record.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a header
A two-byte big-endian length of 00 04 announces four following bytes if that is the record contract. Reading only three means the record is incomplete. See byte order to interpret the header correctly.
Validate against available input
Check the declared value and the application's permitted maximum before allocating or slicing. Fixed-width range gives what the field can express, which can exceed the limit accepted by the reader.[1]
Check completeness before using a decoded size
An unsigned two-byte little-endian field 20 01 gives \(32+256=288\). If the parsed length denotes payload bytes and the source has only one hundred, the record is incomplete. Validate against both remaining bytes and a documented format limit. See length-prefixed records.
Header width: 2 bytes
Header value: 288 payload bytes
Required total without other metadata: 290 bytes
Source size 102 bytes → 188 payload bytes missing
Separate a valid zero-length record from incomplete framing
Two zero header bytes can legitimately describe an empty payload. A single zero byte provides an incomplete header. In a streamed reader, one short read may require continued reading before deciding the source ended. Test all three cases.