basics · beginner · ~10 min
Combine `AND` with the bitwise complement of a shifted mask.
Turn off one specific bit of a 32-bit value, leaving all the others as they were — the mirror image of set_bit.
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).
An unsigned value x (32-bit) and a bit index n in the range 0..31.
Returns x with bit n forced to 0; every other bit keeps its original value.
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
x unchanged.n == 31 clears the highest 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.
An unsigned 32-bit value x and a bit index n in 0..31.
x with bit n forced to 0; other bits unchanged.
No loops; single expression. Use ~(1u << n), not ~(1 << n).
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.