Lesson 37 of 50
cBit Manipulation Techniques
12 mins
Course progress74%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 37 of 50
c12 mins
Keep these ideas in mind as you work through the lesson.
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.
unsigned int count_bits(unsigned int x) {
unsigned int c = 0;
while (x) {
x &= x - 1; // clear least‑significant 1‑bit
++c;
}
return c;
}