Toggling Bits with Bitwise XOR

Bitwise exclusive or produces one where the operands differ. A one in the mask inverts the selected source bit.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a toggle
  2. Use disagreement as a result
  3. Apply the same mask twice to check reversibility
  4. Use a desired-state operation when retries may repeat commands

Trace a toggle

For 0101 and mask 0011, the result is 0110. Applying 0011 again restores 0101. Bitwise or instead preserves previously enabled bits.

Use disagreement as a result

XOR on two same-width flag snapshots gives ones at positions whose memberships changed. It does not classify which bits were set and which cleared. This matches symmetric difference on sets of active flag names.[1]

Apply the same mask twice to check reversibility

XOR with a one flips the selected bit. With input 101100 and mask 001010, the result is 100110. Applying the mask again returns 101100. Toggle is therefore sensitive to repeat calls, unlike setting via OR. See OR for setting flags.

Input             101100
XOR mask          001010
After first XOR   100110
After second XOR  101100

Use a desired-state operation when retries may repeat commands

A message saying “set ready” has a stable desired result under a repeat. A message saying “toggle ready” can reverse the first effect on retry. Test duplicate delivery with the intended contract. See idempotent state transitions.

References

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