Topic 14 of 15 · Expert
Bit Manipulation
AND, OR, XOR, shifts and classic bit tricks.
Concept
Bitwise operators work on individual bits: & AND, | OR, ^ XOR, ~ NOT, << left shift, >> right shift.
Set bit k: x | (1 << k). Clear: x & ~(1 << k). Toggle: x ^ (1 << k). Check: (x >> k) & 1.
x & (x − 1) clears the lowest set bit — used to count set bits and test powers of two. Right-shifting negative signed numbers is implementation-defined; use unsigned.
Cheat sheet
| Trick | Expression |
|---|---|
| Is power of 2 | x && !(x & (x - 1)) |
| Lowest set bit | x & -x |
| Swap without temp | a ^= b; b ^= a; a ^= b; |
| Odd? | x & 1 |
Code (C17)
#include <stdio.h>
int count_bits(unsigned x) {
int c = 0;
while (x) { x &= x - 1; c++; }
return c;
}
int single_number(const int *a, int n) { // all others appear twice
int r = 0;
for (int i = 0; i < n; i++) r ^= a[i];
return r;
}
int main(void) {
printf("%d\n", count_bits(29)); // 11101 -> 4
int a[] = {4, 1, 2, 1, 2};
printf("%d\n", single_number(a, 5)); // 4
return 0;
}Remember
- x ^ x = 0, x ^ 0 = x.
- Use unsigned for bit work.
- x << k multiplies by 2^k.
Interview questions
Check if a number is a power of two.
n > 0 && (n & (n − 1)) == 0.
Find the one number appearing once when others appear twice.
XOR all numbers; pairs cancel out leaving the unique value.
Lesson test
Take an 8-question test on “Bit Manipulation” — concepts, output prediction, bug spotting and interview questions.