Bitwise XOR Operation and Uses
Learn how XOR (^) works and its unique properties: self-inverse, toggling bits, swapping values without a temporary variable, and simple encryption.
Detailed Explanation
Understanding Bitwise XOR (^)
XOR (exclusive OR) returns 1 when the two input bits are different, and 0 when they are the same.
Truth Table
A | B | A ^ B
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0
Worked Example
42 = 00101010
^ 15 = 00001111
──────────────────
37 = 00100101
Key Properties of XOR
Self-inverse:
A ^ B ^ B = A. XORing a value with the same key twice returns the original. This is the basis of simple symmetric encryption and checksums.Identity:
A ^ 0 = A. XORing with zero produces the original value.Self-cancellation:
A ^ A = 0. XORing any value with itself produces zero. This is used to efficiently zero a register in assembly language.Commutativity and associativity: Order does not matter —
A ^ B = B ^ Aand(A ^ B) ^ C = A ^ (B ^ C).
Toggling Bits
XOR selectively flips bits. XORing with 1 flips the target bit; XORing with 0 leaves it unchanged. This makes XOR perfect for toggle operations in flag systems.
Finding the Odd One Out
Given an array where every element appears twice except one, XOR all elements together. The pairs cancel out (A ^ A = 0), leaving only the unique element. This runs in O(n) time with O(1) space — a classic interview question.
Use Case
Cryptographers use XOR as a fundamental building block. The one-time pad encryption scheme XORs plaintext with a random key of equal length: ciphertext = plaintext ^ key. Because XOR is self-inverse, decryption uses the same operation: plaintext = ciphertext ^ key. Modern stream ciphers like ChaCha20 and AES-CTR mode also rely heavily on XOR.