Signed vs. Unsigned Right Shift

Understand the critical difference between >> (arithmetic shift preserving sign) and >>> (logical shift filling with zeros) for negative numbers.

Shift Operations

Detailed Explanation

Arithmetic (>>) vs. Logical (>>>) Right Shift

JavaScript provides both shift operators, and the distinction matters for negative numbers.

Arithmetic Right Shift (>>)

Fills vacated high bits with the sign bit (leftmost bit). This preserves the sign of negative numbers:

  -16 (32-bit) = 11111111111111111111111111110000
  -16 >> 1     = 11111111111111111111111111111000  (-8)
  -16 >> 2     = 11111111111111111111111111111100  (-4)

The mathematical result is floor(n / 2^shift), which rounds toward negative infinity.

Logical Right Shift (>>>)

Always fills vacated high bits with 0, regardless of the sign bit:

  -16 (32-bit) = 11111111111111111111111111110000
  -16 >>> 1    = 01111111111111111111111111111000  (2147483640)
  -16 >>> 2    = 00111111111111111111111111111100  (1073741820)

When Does This Matter?

For positive numbers, both operators produce identical results:

  16 >> 1  = 8
  16 >>> 1 = 8

The difference only appears with negative numbers or when you need to treat a 32-bit value as unsigned.

JavaScript-Specific Behavior

JavaScript numbers are 64-bit floats, but bitwise operators work on 32-bit integers. The >>> operator is the only way to convert a signed 32-bit integer to unsigned in JavaScript:

(-1 >>> 0).toString(16)   // "ffffffff" (4294967295)
(-1 >> 0).toString(16)    // "-1"

Common Use Case: Convert to Unsigned

function toUint32(n) {
  return n >>> 0;
}

This is frequently used in TypedArray operations, hash functions, and binary protocol implementations.

Use Case

Hash function implementations in JavaScript use `>>> 0` to ensure values stay in the unsigned 32-bit range. For example, MurmurHash3 and CRC32 both require unsigned arithmetic. Without `>>> 0`, intermediate values can become negative due to JavaScript's signed 32-bit bitwise semantics, producing incorrect hash values. The pattern `(hash * prime) >>> 0` is standard in JavaScript hashing libraries.

Try It — Bitwise Calculator

Open full tool