Bitwise Operations in C/C++
Why store a bool when 8 of them fit in a byte?
Bitmasks
A bitmask is a binary pattern used to select, set, clear, or toggle specific bits in a variable β usually with the help of bitwise operators.
Here's a refresher in C/C++ style syntax:
#define BIT0 (1 << 0) // 00000001 #define BIT1 (1 << 1) // 00000010 #define BIT2 (1 << 2) // 00000100 ...
If you want to store multiple binary flags in one byte, you can use each bit as a switch:
uint8_t flags = 0;
flags |= BIT2; // turn on bit 2
flags &= ~BIT1; // turn off bit 1
if (flags & BIT2) {
// bit 2 is on
}
Bitmasks in Embedded Engineers
Whether you're toggling an LED or decoding a TCP header, bitmasks are a secret weapon that give you both power and performance. In the world of embedded systems, every byte counts β but the beauty of bit-level thinking goes far beyond microcontrollers.
Some Real Use Cases in Embedded Systems:
- GPIO State Control
-
In firmware for microcontrollers (like STM32, ESP32, etc.), you'll often manipulate GPIO ports directly:
GPIO_PORT |= (1 << 5); // Set pin 5 high GPIO_PORT &= ~(1 << 5); // Set pin 5 low
Why? Because hardware registers expose bit fields β one bit per pin. You can't waste time or RAM with structs or variables.
- Flags in Event Loops
-
Instead of polling multiple boolean variables, embedded loops often use a single byte (or
uint32_t, or...) for flag storage:#define EVENT_BUTTON_PRESS (1 << 0) #define EVENT_TIMEOUT (1 << 1) #define EVENT_ERROR (1 << 2) if (event_flags & EVENT_BUTTON_PRESS) { handle_button(); event_flags &= ~EVENT_BUTTON_PRESS; }Itβs fast, memory-efficient, and avoids branching where unnecessary.