0 day streak
cpp / expert
Snippet

Bitmask-Driven Control Logic

Using bitwise operators and enum classes to manage complex control flow states efficiently. This approach packs multiple boolean flags into a single byte, optimizing both memory and branch prediction.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdint>
enum class Permissions : uint8_t {
Read = 1 << 0, // 0001
Write = 1 << 1, // 0010
Exec = 1 << 2 // 0100
};
inline bool has_permission(uint8_t mask, Permissions p) {
return (mask & static_cast<uint8_t>(p)) != 0;
}
void process_request(uint8_t mask) {
if (has_permission(mask, Permissions::Read)) {
// Execute read logic
}
if (has_permission(mask, Permissions::Write)) {
// Execute write logic
}
}
Breakdown
1
1 << 0
Uses the bit-shift operator to define unique power-of-two values for each flag.
2
mask & static_cast<uint8_t>(p)
Performs a bitwise AND to check if a specific bit is set within the flag mask.