Properties of XOR
- Commutative: A ⊕ B = B ⊕ A
- Associative: A ⊕ ( B ⊕ C ) = ( A ⊕ B ) ⊕ C
- Identity element: A ⊕ 0 = A
- Self-inverse: A ⊕ A = 0
- Parity: for any n bits, A1 ⊕ A2 ⊕ … ⊕ An = 1 (iff the # of 1s is odd)
Uses of XOR
- Toggling
//toggles between two values x and y
for (int n=x; true; n^=(x^y))
cout<<n;
- Swapping without temproary variable
void s(int& a, int& b){ a = a^b; b = a^b; a = a^b; } -
Assembly Language
XOR’ing a register with itself is the fastest way for the compiler to zero the register -
Doubly Linked List
we can store XOR’d value of the previous and next pointers
codes -
Encryption
-
Error Detection
XOR all bits to get a single parity bit and append it to the end of the message. If the received parity bit is different from the calculated one, a single bit has been corrupted. However, this cannot detect if two bits are corrupted. - RAID data protection
Create an additional hard drive which contains the XOR value of all other n drives.
If a failure occurs on one drive, we can restore it from the others. (If 2 drives fail simultaneously, it does not work)