A bitmask is an integer where each bit stands for a yes/no flag. Four patterns do almost everything: set with |=, clear with &= ~mask, toggle with ^=, and test with &. They store many options in one variable.
Remember
#define BIT(n) (1u << (n))
x |= BIT(3); /* set bit 3 */
x &= ~BIT(3); /* clear bit 3 */
x ^= BIT(3); /* toggle bit 3 */
if (x & BIT(3)) {...} /* test bit 3 */
Reference
Cheat Sheet
Keep these facts handy while you work with Bit Manipulation Techniques in C.
Topic
Detail
Set
flags |= MASK
Clear
flags &= ~MASK
Toggle
flags ^= MASK
Power of two
n > 0 && (n & (n - 1)) == 0
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Conditional Operator.
perms = 3
can write
after clear = 1
after toggle = 5
How It Works
READ | WRITE is 001 | 010 = 011 = 3.
perms & PERM_WRITE is non-zero, so the write flag is set.
& ~PERM_WRITE clears bit 1, leaving 1.
^ PERM_EXEC flips bit 2 on, giving 101 = 5.
Example 2 — Count set bits and detect powers of two
n & (n - 1) clears the lowest set bit.
C
#include <stdio.h>
static int popcount(unsigned n) {
int count = 0;
while (n) {
n &= n - 1;
count++;
}
return count;
}
int main(void) {
unsigned n = 181; /* 10110101 */
printf("bits in %u: %d\n", n, popcount(n));
printf("64 power of two? %d\n", (64u & 63u) == 0);
printf("66 power of two? %d\n", (66u & 65u) == 0);
return 0;
}
Output
bits in 181: 5
64 power of two? 1
66 power of two? 0
How It Works
Each loop pass removes one set bit, so the loop runs once per 1-bit.
181 is 10110101, which has five 1s.
A power of two has a single set bit, so n & (n - 1) is 0.
Edge Cases & Pitfalls
Check these before relying on Bit Manipulation Techniques in real programs.
1<<
Using int for bit 31
1 << 31 overflows a signed int. Write 1u << 31 or use uint32_t.
~
Forgetting to mask ~
~mask also flips the high bits. That is fine for &= but surprising when you print it.
Remember
Key Takeaways
Patterns: set |=, clear &= ~, toggle ^=, test &.
Constants: name bits with 1u << n.
Counting:n & (n - 1) drops the lowest set bit.
One line: A bitmask is an integer where each bit stands for a yes/no flag.
Frequently Asked Questions
A bitmask is an integer constant used with bitwise operators to select, set, clear, or test specific bits in another integer. Each bit usually represents one flag.
AND the value with a mask for that bit: if (value & (1u << n)) is true when bit n is set.
Continue with "C Conditional Operator" next. Choose between two values in one expression with ?:. The C Operators hub lists every topic in order.