Packing Two Fields into a Byte
Disjoint bit ranges can store several small unsigned fields. Their width constraints must be checked before combining them.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace two nibbles
Store a counter of 11 in the high four bits and status 3 in the low four bits. The result is binary 10110011 or hexadecimal B3. Hexadecimal bytes expose both nibble values.
Test an oversized input
If status sixteen is allowed into the low field, it occupies a high position and interferes with the counter. Reject it or choose a different layout. Bit field extraction can check the two values after serialization.[1]
Allocate disjoint bit positions before combining
Encode a three-bit type and a five-bit count in one byte. Type five is 101 and count nineteen is 10011. Placing the type in the high bits and OR-ing with the count yields 10110011. See extracting a field for the inverse operations.
Type shift: 5 << 5 → 10100000
Count: 00010011
Packed byte: 10110011
Decoded again: type=5, count=19
Reject invalid values before combining fields
A count of thirty-two spills into the type position if it is neither rejected nor masked. Masking it instead silently changes the count to zero. Tests should cover the maximum supported field values, one step beyond each and a round trip.