Lesson 37 of 50 · c
Bit Manipulation Techniques
Duration: 12 mins
Bit tricks are useful for flags, fast arithmetic, and low‑level protocols.
| Task | Expression |
|---|---|
Set bit n | `x |
Clear bit n | x &= ~(1U << n); |
Toggle bit n | x ^= (1U << n); |
Test bit n | (x & (1U << n)) != 0 |
| Count set bits | Kernighan’s algorithm: while(x){x &= x-1; ++count;} |
| Is power of two? | x && !(x & (x-1)) |
These operations are O(1) and often replace loops.
📚 Example: Counting Bits in an Unsigned Integer
unsigned int count_bits(unsigned int x) {
unsigned int c = 0;
while (x) {
x &= x - 1; // clear least‑significant 1‑bit
++c;
}
return c;
}