Emmanuel Akinfulubi

JavaScriptMath

Why bitwise operators truncate to 32 bits in JavaScript

Advanced · 4 min read

You may have seen code like x | 0 or ~~x used to turn a decimal into a whole number. It works on small numbers. On big ones, it hands back a completely different number, sometimes negative, with no warning. It also turns bad input like NaN into a harmless-looking 0.

In this tutorial you will find out why: every bitwise operator squeezes its input into 32 bits first. You will see what that does to large numbers, fractions and junk values, and then meet the one place where that squeezing is exactly what you want, a string hash. You need to know binary and the operators | and >>>.

What happens before every bitwise operation

JavaScript numbers can hold huge values and decimals. Bitwise operators can't: they only work on 32-bit signed whole numbers. So before |, &, ^, ~, << or >> does anything, JavaScript converts the number. The specification calls this step ToInt32. It does three things:

  1. Drop the fraction, cutting toward zero (1.9 becomes 1, -1.9 becomes -1).
  2. Keep only the bottom 32 bits. This is the same as taking the number modulo 2 ** 32, which is 4294967296.
  3. Read those 32 bits as signed: if the top bit is 1, the number is negative. In practice, anything from 2 ** 31 up comes out negative.

Values that can't be turned into a number at all become 0.

x | 0 ORs with zero, which changes no bits, so it shows you the converted number and nothing else.

Here is the exercise. Have a go yourself first if you like, then read on and we will build it together.

71 Why a bitwise operator hands back a different number

hard

Show what | 0 does to 2 ** 31, to 2 ** 32 + 5, to 1.9, to NaN and to '12abc'. Then write a 32-bit string hash, and show what leaving the | 0 out does to it.

Stuck? Three hints, smallest first
  1. 1. Every bitwise operand goes through ToInt32: modulo 2 ** 32, then anything at or above 2 ** 31 wraps negative.
  2. 2. Anything that cannot be converted to a number becomes 0, not NaN.
  3. 3. A hash loop that never truncates keeps growing, and past 2 ** 53 it stops being exact.

Step 1: big numbers wrap around

Step 1

const int32 = (x) => x | 0;
console.log(int32(2 ** 31));     // -2147483648
console.log(int32(2 ** 32 + 5)); // 5

2 ** 31 is one more than the largest 32-bit signed number, 2147483647. Its top bit is 1, so it is read as negative: the most negative 32-bit number. 2 ** 32 + 5 needs 33 bits. The top one is dropped, and only 5 is left.

Step 2: the unsigned reading

>>> is the one operator that reads the 32 bits as unsigned (never negative):

Step 2

const uint32 = (x) => x >>> 0;
console.log(uint32(-1), int32(uint32(-1))); // 4294967295 -1

-1 is thirty-two 1 bits. Read unsigned, that is 4294967295. Run it through | 0 and the same bits are read as signed, giving -1 again. Same bits, two readings.

Step 3: fractions

Step 3

console.log(int32(1.9), int32(-1.9)); // 1 -1

For values that fit in 32 bits, | 0 cuts toward zero, like Math.trunc. That is why people use it to drop decimals. But only Math.trunc is safe for every size of number: | 0 gives the wrong answer as soon as the value goes past 2147483647.

Step 4: junk becomes 0

Step 4

console.log([NaN, Infinity, '12abc', null, undefined].map(int32)); // [ 0, 0, 0, 0, 0 ]
console.log(int32('12'), int32(true)); // 12 1

Strings and booleans are first turned into numbers. '12' becomes 12, true becomes 1. But '12abc' becomes NaN, and NaN, Infinity, null and undefined all end up as 0.

This makes | 0 a bad way to clean user input. A typo in a form field comes back as 0, which looks like a real value. Check with Number.isFinite instead and handle the bad case yourself.

Step 5: a 32-bit string hash

A hash turns a string into a number, so you can use it as a quick ID or to pick a slot in a table. A classic recipe: start at 0, and for each character, multiply by 31 and add the character's code.

(h << 5) - h is h * 32 - h, which is h * 31. After each step, h |= 0 squeezes the value back into 32 bits:

Step 5

function hash32(s) {
  let h = 0;
  for (let i = 0; i < s.length; i++) {
    h = (h << 5) - h + s.charCodeAt(i);     // h * 31 + code
    h |= 0;                                 // back into a signed 32-bit integer
  }
  return h;
}
const town = 'Abeokuta';
console.log(hash32(town)); // 1391928450

Here the wrap-around is the point. Because the value never leaves 32 bits, the hash stays a fixed size, and the same string always gives the same number.

Step 6: leave the | 0 out

Step 6

function hashDrifting(s) {
  let h = 0;
  for (let i = 0; i < s.length; i++) h = (h << 5) - h + s.charCodeAt(i);
  return h;
}
console.log(hashDrifting(town));                 // 5686895746
console.log(hashDrifting(town) - hash32(town));  // 4294967296

Without h |= 0, only the << part is squeezed into 32 bits. The - h and + code parts use normal arithmetic, so h can grow past 32 bits. Here it ends up exactly 2 ** 32 higher than the proper hash, so it is no longer a 32-bit value. On a longer string the value can climb past Number.MAX_SAFE_INTEGER, where additions stop being exact.

Step 7: a usable index

Some strings hash to a negative number. A negative number is no good as an array index, so finish with >>> 0:

Step 7

console.log(hash32('Ibadan'));         // -2111545271
console.log(uint32(hash32('Ibadan'))); // 2183422025

The bits are the same. Reading them unsigned gives a positive number you can take % of to pick a slot.

The full solution

The answer panel has int32, uint32, hash32 and hashDrifting, and prints the wrapped values, the unsigned round trip, the fractions, the junk values, the coercible ones, the hash of 'Abeokuta' with and without | 0, and the negative hash of 'Ibadan'. Press Run to see the output.

The answer

const int32 = (x) => x | 0;
const uint32 = (x) => x >>> 0;

// A 32-bit hash, kept 32-bit on purpose.
function hash32(s) {
  let h = 0;
  for (let i = 0; i < s.length; i++) {
    h = (h << 5) - h + s.charCodeAt(i);     // h * 31 + code
    h |= 0;                                 // back into a signed 32-bit integer
  }
  return h;
}

// The same loop with the truncation left out.
function hashDrifting(s) {
  let h = 0;
  for (let i = 0; i < s.length; i++) h = (h << 5) - h + s.charCodeAt(i);
  return h;
}

const town = 'Abeokuta';

console.log('2 ** 31 | 0      :', int32(2 ** 31));
console.log('2 ** 32 + 5 | 0  :', int32(2 ** 32 + 5));
console.log('-1 >>> 0, back   :', uint32(-1), int32(uint32(-1)));
console.log('1.9 | 0, -1.9 | 0:', int32(1.9), int32(-1.9));
console.log('junk             :', [NaN, Infinity, '12abc', null, undefined].map(int32));
console.log('coercible        :', int32('12'), int32(true));
console.log('hash32           :', hash32(town), 'unsigned', uint32(hash32(town)));
console.log('without | 0      :', hashDrifting(town), 'which is', hashDrifting(town) - hash32(town), 'larger');
console.log('a negative hash  :', hash32('Ibadan'), '->', uint32(hash32('Ibadan')));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('2 ** 31 wraps to the most negative 32-bit integer', int32(2 ** 31), -2147483648);
test('and 2 ** 32 + 5 loses the whole high word, leaving 5', int32(2 ** 32 + 5), 5);
test('>>> 0 reads those bits as unsigned, and | 0 reads them back', [uint32(-1), int32(uint32(-1))], [4294967295, -1]);
test('| 0 truncates towards zero for values that do fit', [int32(1.9), int32(-1.9)], [1, -1]);
test('anything not convertible becomes 0, never NaN', [NaN, Infinity, '12abc', null, undefined].map(int32), [0, 0, 0, 0, 0]);
test('but a numeric string or a boolean is converted first', [int32('12'), int32(true)], [12, 1]);
test('the hash stays inside 32 bits, so it fits an Int32Array slot', [hash32(town), Math.abs(hash32(town)) <= 2 ** 31], [1391928450, true]);
test('without the | 0 the same loop drifts exactly 2 ** 32 higher', [hashDrifting(town), hashDrifting(town) - hash32(town)], [5686895746, 4294967296]);
test('and >>> 0 turns a negative hash into a usable bucket index', [hash32('Ibadan'), uint32(hash32('Ibadan'))], [-2111545271, 2183422025]);

Every bitwise operator converts its operands with ToInt32 first: take the number modulo 2 ** 32, then read the result as signed, so anything from 2 ** 31 up comes back negative. That single rule explains all of it — 2 ** 31 | 0 is -2147483648, 2 ** 32 + 5 | 0 is 5, and ~~ is not a general truncation. Values that cannot be converted become 0, which is why NaN | 0 and '12abc' | 0 both give 0 and why | 0 is a terrible way to validate input: every bad value looks like a legitimate zero.

The hash is the case where the truncation is the point. h |= 0 keeps the accumulator in range, so the function is closed over 32-bit integers and its output fits an Int32Array. Take it out and the value climbs — here to exactly 2 ** 32 more, since one carry escaped — and on a longer string it climbs past Number.MAX_SAFE_INTEGER, where additions stop being exact and the same input can hash differently depending on how it was built. Hash values are usually wanted as an index, so finish with >>> 0 to make them non-negative.

Common mistakes

  • Using | 0 or ~~ to round big numbers. It only works up to 2147483647. Use Math.trunc.
  • Using | 0 to check input. NaN | 0 and '12abc' | 0 are both 0. Check with Number.isFinite.
  • Forgetting h |= 0 in a hash loop. The value escapes 32 bits and the hash is no longer what you meant.

Try it yourself

  1. Print int32(2 ** 31 - 1), int32(2 ** 31) and int32(2 ** 31 + 1), and explain each one.
  2. Hash your own name with hash32, then turn it into a slot from 0 to 9 with uint32(hash32(name)) % 10.
  3. Compare ~~3000000000.7 with Math.trunc(3000000000.7).

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.