- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Bit Manipulation Basics
Bit Manipulation
Bit Manipulation Basics
Bit tricks are rarely the right tool in application code and are asked about constantly in interviews. Learn the handful that come up; resist using them where a boolean would read better.
The operators
What each one does
javascript
// AND — 1 only where both are 1
console.log(0b1100 & 0b1010) // 0b1000 = 8
// OR — 1 where either is 1
console.log(0b1100 | 0b1010) // 0b1110 = 14
// XOR — 1 where they differ
console.log(0b1100 ^ 0b1010) // 0b0110 = 6
// NOT — flips every bit (and the sign)
console.log(~5) // -6
// Shifts — multiply and divide by powers of two
console.log(5 << 1) // 10
console.log(5 >> 1) // 2