Clearing Selected Bits of a Field

To clear a selected bit while keeping the others, take bitwise and with a mask that has zero at the selected position and ones at the retained positions.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Work within four bits
  2. Check repeated removal
  3. Show the keep mask within a fixed field
  4. Verify preservation with two observable properties

Work within four bits

Clearing the 0010 position of 1110 uses mask 1101 and yields 1100. Inverting the selection mask requires knowing which field width matters. Unsigned field width supplies that context.

Check repeated removal

Clearing it a second time still gives 1100. This differs from toggling and is useful for explicitly turning a setting off. See setting flags with bitwise or for the corresponding enable operation.[1]

Show the keep mask within a fixed field

To clear selected bits in 11010111 using clear mask 00010110, invert that mask within eight bits to get 11101001. AND retains only the allowed positions and yields 11000001. Keeping both masks visible avoids mistaking the bits to clear for those to keep. See bitwise AND.

Value      11010111
Clear mask 00010110
Keep mask  11101001
Result     11000001

Verify preservation with two observable properties

Result AND clear mask must be zero. Every bit outside the clear mask must match the input. Test an empty clear mask and one selecting all bits. Represent signed or unbounded inputs with the intended width before inspecting their binary display.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩