Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 156 ยท Operators

Bitwise Operators

Learn JavaScript's bitwise operators &, |, ^, ~, <<, >> and >>>, how numbers become 32-bit integers, and how to store on/off options as bit flags.

Every number in a computer is stored as a pattern of bits: ones and zeros. Most of the time you never think about them. Bitwise operators are the exception: they let you work on those ones and zeros directly, comparing or shifting them one position at a time.

You won't use them every day. But they show up in real code more often than you might expect: packing several on/off settings into one number, reading the red, green and blue parts of a color, working with binary file formats, and in the occasional "clever" one-liner you'll need to understand when you read someone else's code. This lesson explains what each operator does, the 32-bit conversion that catches people out, and the patterns worth knowing.

Seeing the bits

Before using bitwise operators, it helps to see binary numbers. You already met two tools in Numbers: the 0b prefix writes a number in binary, and toString(2) shows any number in binary. padStart() adds leading zeros so the columns line up:

JS Numbers in binary

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each position is worth twice the one to its right: 1, 2, 4, 8, 16 and so on. 00000101 is 4 + 1, which is 5. Keep the little bits() helper in mind; we'll use it throughout this lesson.

The bitwise operators

Operator Name Each result bit is 1 whenโ€ฆ
a & b AND both bits are 1
a | b OR at least one bit is 1
a ^ b XOR (exclusive or) exactly one bit is 1
~a NOT the bit was 0 (every bit flips)
a << n Left shift bits move n places left, zeros fill in from the right
a >> n Signed right shift bits move n places right, copies of the sign bit fill in
a >>> n Unsigned right shift bits move n places right, zeros fill in

&, | and ^ work column by column: bit 0 of a with bit 0 of b, bit 1 with bit 1, and so on. Nothing carries from one column to the next, which is the big difference from addition.

JS AND, OR and XOR column by column

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Don't confuse these with the logical operators. && and || work with whole values, short-circuit, and return one of their operands. & and | always evaluate both sides, work on individual bits, and always return a number. 5 && 3 is 3, but 5 & 3 is 1.

Numbers become 32-bit integers

JavaScript numbers are normally 64-bit floating-point values. Bitwise operators can't work on that format, so before doing anything they convert each operand to a 32-bit signed integer. The conversion:

  1. Converts the value to a number ("6" becomes 6, true becomes 1, NaN and Infinity become 0).
  2. Drops everything after the decimal point.
  3. Keeps only the lowest 32 bits, wrapping larger values around.

The result is a whole number between โˆ’2,147,483,648 and 2,147,483,647. After the operation the result is converted back to a normal number. This has some visible effects:

JS The 32-bit conversion

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You'll often see x | 0 or ~~x in older code as a "fast" way to drop decimals. It works for small numbers, but it silently breaks above about 2.1 billion, and today's engines make Math.trunc() just as fast. Prefer Math.trunc() (or Math.floor()) for rounding; it says what it means.

Negative numbers and NOT

Signed 32-bit integers store negative numbers using two's complement: the leftmost bit is the sign bit, and -1 is 32 ones. You don't need the theory to use one handy consequence: flipping every bit with ~ turns x into -(x + 1).

JavaScript
~0;     // -1
~5;     // -6
~-1;    // 0

That is why old code wrote if (~text.indexOf("x")): indexOf() returns -1 when nothing is found, and ~-1 is 0, which is falsy. Today text.includes("x") says the same thing clearly. Use that instead.

To see the full 32 bits of a negative number, convert it to unsigned first with >>> 0 (explained below): (-1 >>> 0).toString(2) prints 32 ones.

Shifting bits

The shift operators slide the whole bit pattern left or right. Shifting left by one doubles a number; shifting right by one halves it and drops the remainder:

JS Left and right shifts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three details matter:

  • >> keeps the sign by copying the sign bit into the empty positions, so negative numbers stay negative. >>> always fills with zeros, so its result is never negative.
  • Shift counts wrap at 32. Only the lowest five bits of the count are used, so x << 32 is the same as x << 0. Don't use shifts for powers of two above 2ยณโฐ; use 2 ** n.
  • 1 << 31 is negative, because bit 31 is the sign bit. Use bits 0 to 30 for flags if you want to avoid surprises.

Bit flags: many booleans in one number

The most common real use of bitwise operators is bit flags. Each option gets one bit, and a single number stores which options are on. File permissions, keyboard modifier keys and game-object states are classic examples.

Give each flag its own power of two, usually written as a shift so the bit position is obvious:

JS Permissions as bit flags

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The four moves to remember:

Goal Code
Turn a flag on value |= FLAG
Turn a flag off value &= ~FLAG
Toggle a flag value ^= FLAG
Test a flag (value & FLAG) !== 0

All bitwise operators have compound assignment forms: &=, |=, ^=, <<=, >>= and >>>=. You can still use the logical assignment operators for whole values; these are their bit-level cousins.

Should you use flags? For a handful of options in everyday app code, an object such as { read: true, write: false } or a Set is easier to read and debug. Flags shine when you store or send many records compactly, or when an API already uses them, such as the buttons property of mouse events, where 1 is the main button, 2 the secondary and 4 the middle.

Other practical patterns

A few more patterns you'll meet in the wild:

JS Masks, colors and parity

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A mask is a number whose 1 bits mark the positions you care about. & 0xff keeps the lowest eight bits and clears the rest; combining it with a shift extracts any field from a packed value. You'll use the same ideas with binary data in Typed Arrays and Binary Data.

Pitfalls

Precedence. Bitwise &, ^ and | bind more loosely than ===. This line looks right but isn't:

JavaScript
if (perms & WRITE === WRITE) { โ€ฆ }
// means: perms & (WRITE === WRITE)  โ†’  perms & true  โ†’  perms & 1

Always wrap the bitwise part in parentheses: (perms & WRITE) === WRITE. The full precedence table is in the next lesson.

Typos for && and ||. if (a & b) instead of if (a && b) often seems to work, then fails for values like 2 & 1, which is 0. Linters flag this.

Large numbers. Anything above 2ยณยน โˆ’ 1 wraps around. IDs, timestamps in milliseconds (Date.now() is far above 2ยณยฒ) and money in cents can all exceed it.

BigInt. BigInt values support &, |, ^, ~, << and >> with no 32-bit limit, so (1n << 40n) | 1n works. Both operands must be BigInts, and >>> throws a TypeError because BigInts have no fixed width.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is 6 & 3?

    6 is 110 and 3 is 011. Only the middle column has a 1 in both, so the result is 010, which is 2.
  2. 2. Which line turns the WRITE flag off without touching the other flags?

    ~WRITE has every bit set except the WRITE bit, so ANDing with it clears that one bit. Subtracting only works if the flag was already on.
  3. 3. What does 3_000_000_000 | 0 produce?

    Bitwise operators convert operands to 32-bit signed integers. Values above 2,147,483,647 wrap into the negative range. Use Math.trunc() to drop decimals safely.
  4. 4. Why is if (flags & READ === READ) a bug?

    Bitwise AND has lower precedence than strict equality. Write (flags & READ) === READ.
  5. 5. How do >> and >>> differ?

    Signed right shift copies the sign bit into the empty positions. Unsigned right shift fills with zeros, which is why -1 >>> 0 is 4294967295.

Summary

  • Bitwise operators work on individual bits: & (AND), | (OR), ^ (XOR), ~ (NOT), and the shifts <<, >> and >>>.
  • Operands are first converted to 32-bit signed integers: decimals are dropped and large values wrap around.
  • ~x equals -(x + 1); >> keeps the sign while >>> fills with zeros; shift counts wrap at 32.
  • Bit flags store many booleans in one number: |= to set, &= ~ to clear, ^= to toggle, & to test.
  • Shift and mask ((value >> 8) & 0xff) to pack and unpack fields such as color channels.
  • Wrap bitwise expressions in parentheses when comparing, prefer Math.trunc() over | 0, and use BigInt for wide values.

Next: More Operators and Precedence โ€” typeof, in, delete, the comma operator and the full precedence table.