basics · beginner · ~10 min

Clear a single bit

Combine `AND` with the bitwise complement of a shifted mask.

Challenge

Implement unsigned clear_bit(unsigned x, int n) that returns x with bit n set to 0 (other bits unchanged).

  • Bits are indexed from 0 (least-significant).
  • 0 <= n < 32.

Examples

clear_bit(0b1111, 0) -> 0b1110
clear_bit(0b1010, 1) -> 0b1000
clear_bit(0b0000, 5) -> 0b0000  // already 0

Edge cases

  • Bit already 0 — output equals input.
  • n == 31 clears the high-order bit.

Why this matters

The mirror of set_bit. Hardware registers, packet headers, and option flags all rely on the &= ~mask idiom to turn a single bit off without disturbing its neighbours.

Input format

x unsigned 32-bit; n in 0..31.

Output format

x with bit n forced to 0.

Constraints

No loops; single expression.

Starter code

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

Common mistakes

~(1 << n) is signed and undefined at n == 31. Use ~(1u << n). Confusing AND with OR — x & ~mask clears; x | mask sets.

Edge cases to handle

n == 0; n == 31; bit already cleared.

Complexity

O(1).

Background lessons

Up next

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