cpp / intermediate
Snippet
Type-Safe Bit Manipulation with Bitset
std::bitset provides a memory-efficient way to manage a fixed-size sequence of bits. Unlike manual bitwise operations on integers, it offers methods like 'test', 'set', and 'flip' which provide better abstraction and safety for handling flags.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>#include <bitset>int main() {// Represents 8 bits, initialized to zerostd::bitset<8> flags;flags.set(1); // Set bit at index 1flags.flip(3); // Toggle bit at index 3if (flags.test(1)) {std::cout << "Bit 1 is active: " << flags << std::endl;}return 0;}
Breakdown
1
std::bitset<8> flags;
Allocates a compact structure holding 8 individual bits.
2
flags.test(1)
Checks if the bit at the specified position is set, returning a boolean.