basics · beginner · ~10 min
Combine `AND` with the bitwise complement of a shifted mask.
Implement unsigned clear_bit(unsigned x, int n) that returns x with bit n set to 0 (other bits unchanged).
0 <= n < 32.clear_bit(0b1111, 0) -> 0b1110
clear_bit(0b1010, 1) -> 0b1000
clear_bit(0b0000, 5) -> 0b0000 // already 0
n == 31 clears the high-order bit.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.
x unsigned 32-bit; n in 0..31.
x with bit n forced to 0.
No loops; single expression.
unsigned clear_bit(unsigned x, int n) { /* TODO */ return x; }
~(1 << n) is signed and undefined at n == 31. Use ~(1u << n). Confusing AND with OR — x & ~mask clears; x | mask sets.
n == 0; n == 31; bit already cleared.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.