basics · beginner · ~10 min
Use `XOR` with a one-hot mask to flip a bit.
Implement unsigned toggle_bit(unsigned x, int n) that returns x with bit n flipped.
0 <= n < 32.toggle_bit(0b0000, 0) -> 0b0001
toggle_bit(0b0001, 0) -> 0b0000
toggle_bit(0b1010, 3) -> 0b0010
XOR with a one-hot mask is the universal 'flip this bit' primitive: blinking-LED demos, parity calculations, and reversible scrambling all build on it.
x unsigned; n in 0..31.
x with bit n flipped.
O(1); single expression.
unsigned toggle_bit(unsigned x, int n) { /* TODO */ return x; }
Confusing ^ (XOR) with & or |. Forgetting the u suffix on the literal.
Two toggles cancel; toggle twice and you should get the original.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.