Bitwise calculator
AND, OR, XOR, NOT and shifts, shown in binary, decimal and hex.
0x0000000C · 2 bits set
0x0000000A · 2 bits set
Operations
| Operation | Decimal | Hex | Binary |
|---|---|---|---|
| AND (a & b) Bit set only where both are set — masking | 8 | 0x00000008 | 00000000 00000000 00000000 00001000 |
| OR (a | b) Bit set where either is set — combining flags | 14 | 0x0000000E | 00000000 00000000 00000000 00001110 |
| XOR (a ^ b) Bit set where exactly one is set — toggling | 6 | 0x00000006 | 00000000 00000000 00000000 00000110 |
| NOT a (~a) Every bit inverted — note the sign | -13 | 0xFFFFFFF3 | 11111111 11111111 11111111 11110011 |
| AND NOT (a & ~b) Clear the bits of b from a | 4 | 0x00000004 | 00000000 00000000 00000000 00000100 |
| Left shift (a << 2) Multiply by 2ⁿ | 48 | 0x00000030 | 00000000 00000000 00000000 00110000 |
| Sig2ed right shift (a >> n) Divide by 2ⁿ, keeping the sign | 3 | 0x00000003 | 00000000 00000000 00000000 00000011 |
| U2signed right shift (a >>> n) Fills with zeros from the left | 3 | 0x00000003 | 00000000 00000000 00000000 00000011 |
How it works
JavaScript's bitwise operators convert their operands to 32-bit signed integers, act on the
bits, and convert back. That conversion is why ~5 is −6 rather than a large
positive number, and why values above 2³¹ behave unexpectedly.
Two's complement
Negative numbers are represented by inverting all bits and adding one. The top bit is the sign,
so 0xFFFFFFFF is −1 rather than 4,294,967,295. The unsigned right shift >>> is the one operator that treats the value as unsigned, which is the
standard way to coerce a number to a uint32.
Bit flags
Packing booleans into one integer is still the standard way to represent permission sets and feature flags:
set: flags |= FLAG
clear: flags &= ~FLAG
toggle: flags ^= FLAG
test: (flags & FLAG) !== 0 Shifts as arithmetic
x << n multiplies by 2ⁿ and x >> n divides by it, rounding
toward negative infinity. Compilers do this transformation themselves, so writing shifts for
speed in high-level code buys nothing and costs readability.
XOR tricks
XOR is its own inverse: a ^ b ^ b === a. That underpins one-time-pad encryption,
simple checksums, and the classic “find the non-duplicated element” puzzle — XOR every value in
a list and the pairs cancel out.