JS Bitwise
Bitwise operators treat numbers as 32-bit integers. They're rare in everyday business logic but unbeatable for flags, hash mixing, and graphics math.
The operators
| Operator | Means | Example |
|---|---|---|
& | AND | 0b1100 & 0b1010 → 0b1000 |
| | OR | 0b1100 | 0b1010 → 0b1110 |
^ | XOR | 0b1100 ^ 0b1010 → 0b0110 |
~ | NOT (unary) | ~5 → -6 |
<< | Shift left (× 2 per step) | 1 << 4 → 16 |
>> | Arithmetic shift right | -8 >> 1 → -4 |
>>> | Unsigned shift right | -1 >>> 0 → 4294967295 |
Flag fields
JS
const PERMISSIONS = { READ: 1, WRITE: 2, ADMIN: 4 };
// Combine
let mine = PERMISSIONS.READ | PERMISSIONS.WRITE; // 3
// Test
if (mine & PERMISSIONS.READ) { /* yes */ }
// Add / remove
mine |= PERMISSIONS.ADMIN;
mine &= ~PERMISSIONS.WRITE;
Handy patterns
| Pattern | Trick |
|---|---|
| Floor to integer (positives) | x | 0 or ~~x |
| Multiply by 2 / power of 2 | x << n |
| Check odd | x & 1 |
| Swap without temp | a ^= b; b ^= a; a ^= b; (don't actually do this) |
Warning: Bitwise operators convert to 32-bit signed integers. Anything outside that range loses precision:
(2 ** 32) | 0 = 0. Use BigInt for larger needs.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Bitwise!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Use the bitwise OR to combine two permission flags.
const mine = READ
WRITE;
A single character.
Discussion
Loading…