cpp / expert
Snippet
Manual Bit-Field Packing for Memory-Constrained State
Expert memory management using bitwise operations to pack multiple logical fields into a single byte. This is crucial for embedded systems, high-frequency trading, or networking where every byte of overhead matters.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
struct CompactState {uint8_t data;void setReady(bool b) { data = (data & ~0x01) | (b ? 0x01 : 0x00); }bool isReady() const { return data & 0x01; }void setErrorCode(uint8_t code) { data = (data & ~0xFE) | ((code & 0x7F) << 1); }uint8_t getErrorCode() const { return (data >> 1) & 0x7F; }};// Total size: 1 byte for 1 bool and a 7-bit error code.
Breakdown
1
data & ~0x01
Clears the first bit while preserving all other bits in the byte.
2
(code & 0x7F) << 1
Masks the input to 7 bits and shifts it to occupy the upper bits of the byte.