c / intermediate
Snippet
Bitwise Flag Manipulation
Bitwise operators are used to store multiple boolean flags within a single integer, which is highly memory-efficient and fast.
snippet.c
1
2
3
4
5
6
7
8
#define READ (1 << 0)#define WRITE (1 << 1)unsigned char permissions = 0;permissions |= READ;if (permissions & READ) {/* logic */}
Breakdown
1
(1 << 0)
Shifts the bit 1 to the left by 0 positions, creating a mask for the first bit.
2
permissions |= READ;
Uses the OR operator to set the READ bit without affecting other bits.
3
permissions & READ
Uses the AND operator to check if the specific READ bit is currently set.