basics · beginner · ~10 min

Toggle a single bit

Use `XOR` with a one-hot mask to flip a bit.

Challenge

Implement unsigned toggle_bit(unsigned x, int n) that returns x with bit n flipped.

  • If the bit was 0 it becomes 1 and vice versa.
  • 0 <= n < 32.

Examples

toggle_bit(0b0000, 0) -> 0b0001
toggle_bit(0b0001, 0) -> 0b0000
toggle_bit(0b1010, 3) -> 0b0010

Edge cases

  • Two toggles return the original value.

Why this matters

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.

Input format

x unsigned; n in 0..31.

Output format

x with bit n flipped.

Constraints

O(1); single expression.

Starter code

unsigned toggle_bit(unsigned x, int n) { /* TODO */ return x; }

Common mistakes

Confusing ^ (XOR) with & or |. Forgetting the u suffix on the literal.

Edge cases to handle

Two toggles cancel; toggle twice and you should get the original.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.