Programming•9 min read
Bitwise Operations Guide: AND, OR, XOR Explained
Master bitwise operations for programming. Learn AND, OR, XOR, NOT, and bit manipulation techniques.
By Andy Pham
Bitwise Operations Guide: AND, OR, XOR Explained
Bitwise operations manipulate individual bits and are fundamental for low-level programming, cryptography, and optimization.
Bitwise Operators
AND (&)
Returns 1 if both bits are 1.
1010 (10)
& 1100 (12)
------
1000 (8)
OR (|)
Returns 1 if either bit is 1.
1010 (10)
| 1100 (12)
------
1110 (14)
XOR (^)
Returns 1 if bits are different.
1010 (10)
^ 1100 (12)
------
0110 (6)
NOT (~)
Inverts all bits.
~ 1010 (10)
------
0101 (-11 in two's complement)
Shift Operations
// Left shift (multiply by 2^n)
5 << 1 // 10 (5 * 2)
5 << 2 // 20 (5 * 4)
// Right shift (divide by 2^n)
20 >> 1 // 10 (20 / 2)
20 >> 2 // 5 (20 / 4)
Truth Tables
AND Truth Table
| A | B | A & B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
OR Truth Table
| A | B | A | B |
|---|---|--------|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
XOR Truth Table
| A | B | A ^ B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
Practical Applications
Check if Even/Odd
function isEven(n) {
return (n & 1) === 0;
}
Swap Without Temp Variable
function swap(a, b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
return [a, b];
}
Check/Set/Clear Bits
// Check if bit is set
function isBitSet(n, pos) {
return (n & (1 << pos)) !== 0;
}
// Set a bit
function setBit(n, pos) {
return n | (1 << pos);
}
// Clear a bit
function clearBit(n, pos) {
return n & ~(1 << pos);
}
// Toggle a bit
function toggleBit(n, pos) {
return n ^ (1 << pos);
}
Permissions (Flags)
const READ = 1; // 001
const WRITE = 2; // 010
const EXECUTE = 4; // 100
// Set permissions
let permissions = READ | WRITE; // 011
// Check permission
if (permissions & READ) {
console.log('Can read');
}
// Add permission
permissions |= EXECUTE; // 111
// Remove permission
permissions &= ~WRITE; // 101
Try Our Bitwise Tools
- AND Calculator - Bitwise AND
- OR Calculator - Bitwise OR
- XOR Calculator - Bitwise XOR
Conclusion
Bitwise operations are powerful for optimization, flags, and low-level programming.