basics · beginner · ~10 min

Toggle a single bit

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

Challenge

Flip one specific bit of a 32-bit value: a 0 becomes 1 and a 1 becomes 0, leaving all other bits unchanged.

Task

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).

Input

An unsigned value x (32-bit) and a bit index n in the range 0..31.

Output

Returns x with bit n flipped; every other bit keeps its original value.

Example

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

Edge cases

  • Toggling the same bit twice returns the original value (XOR is self-inverse).

Rules

  • No loops — a single XOR-with-mask expression suffices.

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

An unsigned 32-bit value x and a bit index n in 0..31.

Output format

x with bit n flipped; other bits unchanged.

Constraints

O(1); single expression. Shift 1u (unsigned), not 1.

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.