basics · beginner · ~10 min

Clear a single bit

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

Challenge

Turn off one specific bit of a 32-bit value, leaving all the others as they were — the mirror image of set_bit.

Task

Implement unsigned clear_bit(unsigned x, int n) that returns a copy of x with bit n set to 0. 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 forced to 0; every other bit keeps its original value.

Example

clear_bit(0xF, 0)          ->   0xE     (binary 1111 -> 1110)
clear_bit(0xA, 1)          ->   0x8     (binary 1010 -> 1000)
clear_bit(0x0, 5)          ->   0x0     (bit already 0: no change)
clear_bit(0xFFFFFFFF, 31)  ->   0x7FFFFFFF

Edge cases

  • Clearing a bit that is already 0 returns x unchanged.
  • n == 31 clears the highest bit.

Rules

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

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

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

Output format

x with bit n forced to 0; other bits unchanged.

Constraints

No loops; single expression. Use ~(1u << n), not ~(1 << n).

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.