Home / Learn Embedded C / Clearing a Bit

Clearing a Bit

Turning off exactly one bit, using AND with an inverted mask.

The short versionTurning off exactly one bit, using AND with an inverted mask.

Theory in plain words

Clearing bit 2 of 0b00000111start: 0b00000111mask = ~(1 << 2) =0b11111011value &= maskresult: 0b00000011
Clearing bit 2 of 0b00000111

In plain terms

Clearing bit N to 0 (without changing any other bit) is done with register &= ~(1 << N) — AND-ing with a mask that has every bit set except bit N.

Why we use it

Turning off one GPIO pin, or disabling one feature flag, needs exactly the mirror-image operation of setting a bit — AND forces bits to 0 where the mask has a 0, and leaves everything else untouched.

Under the hood

~(1 << N) flips the single-bit mask into "all 1s except position N"; AND-ing with that forces position N to 0 while every 1 elsewhere in the mask leaves the corresponding bit in register unchanged.

Real-world use

  • GPIO pin control
  • Disabling a feature flag
  • Register configuration

Try it

Clearing one pin while keeping the others setC: edit and run

Pin 2 stays on (bit value 0x04) while pin 5 is cleared — the mirror image of the "setting a bit" lesson.

Try it: clearing an entire field with a multi-bit mask

Clearing a 2-bit mode field before setting a new valueC: edit and run

The same &= ~mask pattern works whether the mask covers one bit or several adjacent bits forming a field.

Quick quiz

1. What operator/pattern clears bit N to 0 without affecting other bits?