Home / Learn Embedded C / Packing Flags into a Single Byte
Packing Flags into a Single Byte
Representing up to 8 independent true/false settings in one small variable.
Breaking it down
What it is
Packing several independent boolean flags into one byte (one bit per flag) saves RAM compared to 8 separate variables, and mirrors exactly how real status/control registers are organized.
Why it matters
A device with several independent settings (Wi-Fi connected? logging enabled? low battery?) can track all of them in a single byte instead of 8 separate int or bool variables, each of which might otherwise cost 1-4 bytes alone.
Mechanically speaking
Each named flag gets its own bit position (via a #define or const int mask); set/clear/check uses exactly the OR/AND-with-NOT/AND patterns from earlier in this group.
Shows up in
- Device state tracking
- Configuration flags
- Status registers
Try it
All 4 flags live in one byte — on a device with dozens of settings, this adds up to real memory savings.
Try it: toggling one flag and clearing another
FLAG_B and FLAG_D are untouched throughout — only the two targeted flags change, exactly as packed flag bytes are meant to behave.
Check yourself
1. Why pack 8 independent boolean flags into one byte instead of 8 separate variables?
One packed byte can represent 8 flags in the space a single variable would otherwise take, saving real RAM on a constrained chip.