Using Bitwise And to Read Selected Bits

Bitwise and retains a one only at positions that are one in both operands. A mask can isolate part of a field.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Work one pattern
  2. Test one selected bit
  3. Compare only the bit positions selected by the mask
  4. Choose a test for any versus all selected flags

Work one pattern

For value 10110100 and mask 00001111, the result is 00000100. The mask retains four lower bits. Binary numerals interpret those bits as four.

Test one selected bit

To test position five, use a mask with a single one in that position and compare the result to zero. Testing the result for equality to one checks the wrong numeric value for most positions. See Boolean truth testing.[1]

Compare only the bit positions selected by the mask

Starting with 10110110, mask 00001111 selects the low four bits. The result is 00000110 because each outside position is paired with zero. A mask selecting bits six and five can retain them at their original positions for a flag comparison. See extracting a packed field.

Input   10110110
Mask    00001111
AND     00000110
Low field value: 6

Choose a test for any versus all selected flags

Testing whether value & mask is nonzero asks whether any selected flag is set. Comparing it to the full mask tests whether all are set. A zero mask makes the all test trivially true. Test each rule using a partial match.

References

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