basics · beginner · ~10 min
Use `XOR` with a one-hot mask to flip a bit.
Flip one specific bit of a 32-bit value: a 0 becomes 1 and a 1 becomes 0, leaving all other bits unchanged.
Implement unsigned toggle_bit(unsigned x, int n) that returns a copy of x with bit n inverted. Bits are numbered from 0 (the least-significant bit).
An unsigned value x (32-bit) and a bit index n in the range 0..31.
Returns x with bit n flipped; every other bit keeps its original value.
toggle_bit(0x0, 0) -> 0x1 (binary 0000 -> 0001)
toggle_bit(0x1, 0) -> 0x0 (binary 0001 -> 0000)
toggle_bit(0xA, 3) -> 0x2 (binary 1010 -> 0010)
toggle_bit(0x0, 31) -> 0x80000000
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.
An unsigned 32-bit value x and a bit index n in 0..31.
x with bit n flipped; other bits unchanged.
O(1); single expression. Shift 1u (unsigned), not 1.
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.