Bit positions start at zero on the right. A single-bit mask for position k is 1 shifted left by k. For k = 3, the 8-bit mask is 00001000.
Use x | mask to set a bit, x & ~mask to clear it, and x ^ mask to toggle it. OR with zero and AND with one preserve all the other positions.
A field mask has several adjacent ones. To extract a field, shift it down and AND with a low-bit mask. This is the foundation of packed flags, instruction encodings, and compact data formats.
Explain it before you practise
Look away from the example. Explain why it works and predict a boundary case. Then check your reasoning.
How can you prove that clearing bit k leaves every other bit unchanged, even when bit k was already zero?
Check your reasoning
The mask ~(1 << k) has 0 at k and 1 everywhere else within the word. AND with 0 clears k; AND with 1 preserves each other bit. Clearing an already-zero bit still gives zero.
Cement this knowledge
Solve ten fresh questions without the worked example. Mistakes return during the session; spaced review helps you recall the method on later days.
Practice this topic →