Home / Learn Embedded C / Clearing a Bit
Clearing a Bit
Turning off exactly one bit, using AND with an inverted mask.
Theory in plain words
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
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
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?
AND-ing with every bit set except N forces N to 0 while leaving all other bits as they were.