JavaScript XOR: Toggling, Swapping, and More
You might have encountered the XOR operator (^
) in JavaScript, but its purpose and practical applications can often seem a bit mysterious. Let's demystify this bitwise operator and explore its hidden potential.
What is XOR?
XOR stands for "exclusive OR." It's a bitwise operator that compares corresponding bits of two operands. If the bits are different, the result is 1; if they are the same, the result is 0. Here's a truth table to illustrate:
A | B | A^B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Purpose and When to Use XOR:
- Toggling Bits
XOR is perfect for flipping bits. If you XOR a bit with 1, it will always toggle its value. This is incredibly useful for managing boolean flags or bitmasks.
Example:
let flag = true;
flag ^= true; // flag is now false
flag ^= true; // flag is now true
- Swapping Variables Without a Temporary Variable
XOR allows you to swap the values of two variables without needing a temporary variable. This is a classic bit manipulation technique.
Example:
let a = 5; // 0101
let b = 10; // 1010
a ^= b; // a = 15 (1111)
b ^= a; // b = 5 (0101)
a ^= b; // a = 10 (1010)
console.log("a:", a, "b:", b); // Output: a: 10 b: 5
- Detecting Differences
XOR can be used to determine if two values are different. If the result of XOR is non-zero, the values are different.
- Cryptography (Simple Examples)
XOR is used in some simple encryption algorithms because it's reversible. XORing a value with a key encrypts it, and XORing the encrypted value with the same key decrypts it.
Example:
let message = "Hello";
let key = 42;
let encrypted = "";
for(let i = 0; i < message.length; i++){
encrypted += String.fromCharCode(message.charCodeAt(i) ^ key);
}
console.log("Encrypted:", encrypted);
let decrypted = "";
for(let i = 0; i < encrypted.length; i++){
decrypted += String.fromCharCode(encrypted.charCodeAt(i) ^ key);
}
console.log("Decrypted:", decrypted);
Conclusion
XOR, while seemingly simple, is a powerful tool in JavaScript's bitwise arsenal. Understanding its purpose and applications can open up new possibilities for efficient and elegant code.
Happy Coding!
Comments ()