basics · beginner · ~15 min

Clear a bit

Force a single bit to 0.

Challenge

Implement:

unsigned clear_bit(unsigned x, int i);

Return x with bit i set to 0. i is in 0..31.

Input format

x and a bit index i.

Output format

x with bit i = 0.

Constraints

i in 0..31.

Starter code

#include <stddef.h>
/* Return x with bit i set to 0. i in 0..31. */
unsigned clear_bit(unsigned x,int i){ (void)i; return x; }

Common mistakes

Forgetting to invert the mask (& mask clears everything else instead).

Edge cases to handle

Clearing an already-clear bit is a no-op.

Background lessons

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