Using Bitwise Or to Set Flags

Bitwise or sets every position that is already one in either operand, so it can enable a flag while preserving other enabled flags.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace an update
  2. Check the assigned positions
  3. Set one flag without discarding unrelated state
  4. Keep a test for changes outside the intended positions

Trace an update

For flags 0101 and mask 0010, the result is 0111. Applying the same mask again leaves 0111. This is idempotence for the stored bit pattern.

Check the assigned positions

Store one documented mask per independent flag. Combining flags should use the declared masks rather than assuming they occupy consecutive bits. Use bitwise and to test each preserved and newly set flag.[1]

Set one flag without discarding unrelated state

If status 01010001 gains flag 00000100, OR gives 01010101. The previous high and low set bits survive. Reapplying the same mask keeps the same result. An assignment to the mask alone would discard the old set positions. See setting and clearing via masks.

Value      01010001
Set mask   00000100
Result     01010101
Set again  01010101

Keep a test for changes outside the intended positions

When several flags are set together, combine their masks first. Compare the masked-off region before and after the operation to verify it was preserved. Check an already set flag and a word whose unrelated flags are all clear.

References

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