Emmanuel Akinfulubi

JavaScriptMath

Unsigned right shift (>>>) and 32-bit limits in JavaScript

Intermediate · 4 min read

Permission settings, game input flags, color channels and fast hash functions all work directly on the bits of a number, the ones and zeros it is stored as. JavaScript has seven operators for this: &, |, ^, ~, <<, >> and >>>. They are fast and compact, but they all hit the same wall at 32 bits.

In this tutorial you will try each operator on small numbers and check the answers by hand. Then you will hit the 32-bit wall on purpose, and use what you learn to write a power-of-two test and a bit counter. You need to know binary numbers (5 is 101) and arrow functions.

The operators in plain words

Write 5 and 3 in binary, one above the other: 101 and 011. Most of the operators compare them column by column.

  • & (AND) gives 1 where both have a 1: 001, which is 1.
  • | (OR) gives 1 where either has a 1: 111, which is 7.
  • ^ (XOR, "exclusive or") gives 1 where exactly one has a 1: 110, which is 6.
  • ~ (NOT) flips every bit of one number.
  • << shifts bits left, and >> and >>> shift them right.

The 32-bit wall

JavaScript numbers are normally 64-bit decimals. Before any bitwise operator runs, JavaScript converts its inputs to 32-bit signed integers: whole numbers from -2147483648 to 2147483647. "Signed" means the leftmost of the 32 bits is the sign bit: when it is 1, the number counts as negative. The result is converted back afterward. Everything odd in this lesson comes from that conversion.

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

85 Bitwise operators, and the 32-bit wall behind them

fair

Apply & | ^ ~ << >> >>> to small numbers and check each result by hand. Then show that 1 << 31 is negative, that 1 << 32 is 1, and write a power-of-two test and a bit counter that both use this deliberately rather than by accident.

Stuck? Three hints, smallest first
  1. 1. ~n is -(n + 1). Every bitwise operand becomes a signed 32-bit integer first.
  2. 2. >>> is the only one that produces an unsigned result, so -1 >>> 0 is large and positive.
  3. 3. A power of two has one bit set, so n & (n - 1) clears it and leaves 0.

Step 1: AND, OR and XOR

Step 1

console.log(5 & 3, 5 | 3, 5 ^ 3); // 1 7 6

These match the columns worked out above.

Step 2: NOT and the shifts

Step 2

console.log(~5, 5 << 1, 5 >> 1); // -6 10 2
console.log(~~3.7, ~~-3.7);       // 3 -3

~5 is -6. That looks odd, but flipping every bit of a signed 32-bit number always gives -(n + 1). Shifting left by one doubles a number (101 becomes 1010, which is 10). Shifting right by one halves it and drops the remainder (101 becomes 10, which is 2).

~~x flips the bits twice, which cancels out. What's left is the 32-bit conversion, which cuts off the decimals toward zero. People use it as a short Math.trunc, but only for numbers inside the 32-bit range.

Step 3: >> versus >>>

Step 3

console.log(-1 >> 0, -1 >>> 0); // -1 4294967295

In 32 bits, -1 is stored as thirty-two 1s. >> keeps the sign bit, so the answer is still -1. >>> is the unsigned right shift: it reads the same 32 bits as a plain positive number, so you get 4294967295, which is 2 ** 32 - 1. It is the only bitwise operator that gives an unsigned result.

Step 4: walking into the wall

Step 4

console.log(1 << 30, 1 << 31, 1 << 32); // 1073741824 -2147483648 1
console.log(2 ** 31 | 0, 2 ** 32 | 0);  // -2147483648 0

Each left shift doubles, until 1 << 31. That puts the 1 in the sign bit, so the number turns negative. 1 << 32 is 1 again, because the shift count is taken modulo 32, and a shift of 0 does nothing. The same wall shows up in | 0: 2 ** 31 turns negative and 2 ** 32 becomes 0.

Step 5: a power-of-two test

A power of two (1, 2, 4, 8...) has exactly one bit set. Subtracting 1 turns that bit off and every bit below it on, so 8 (1000) minus 1 is 7 (0111). AND them together and you get 0.

Step 5

const isPowerOfTwo = (n) => n > 0 && (n & (n - 1)) === 0;
console.log([1, 2, 3, 4, 1024, 0, -4].map(isPowerOfTwo)); // [ true, true, false, true, true, false, false ]

The n > 0 guard matters. Without it, 0 would pass, because 0 & -1 is 0.

Step 6: count the bits

Counting how many bits are 1 is called a popcount (population count). Look at the last bit with & 1, then shift right and repeat.

Step 6

const popcount = (n) => {
  let bits = n >>> 0;
  let count = 0;
  while (bits) {
    count += bits & 1;
    bits >>>= 1;
  }
  return count;
};
console.log(popcount(255), popcount(1024), popcount(-1)); // 8 1 32

n >>> 0 uses the unsigned view on purpose. With >> instead, -1 would stay -1 forever, because >> copies the sign bit in from the left, and the loop would never end. With >>>, zeros come in from the left and the loop stops after 32 rounds.

Step 7: flags, where bitwise code reads well

Give each permission its own bit, and one number can hold a whole set of them.

Step 7

const READ = 1;
const WRITE = 2;
const ADMIN = 4;
const grant = READ | ADMIN;
const can = (flags, flag) => (flags & flag) !== 0;
console.log(grant, can(grant, READ), can(grant, WRITE), can(grant, ADMIN)); // 5 true false true

| adds a permission and & tests for one. The answer also swaps two numbers with three XORs, xorSwap(9, 4) giving [4, 9]. It is a neat trick, but [a, b] = [b, a] is clearer.

The full solution

The answer panel has isPowerOfTwo, popcount, xorSwap and the permission flags, and prints every operator, the 32-bit wall cases and the flag checks. Press Run to see the output.

The answer

// A shift count is taken modulo 32, which is why 1 << 32 is 1 again.
const isPowerOfTwo = (n) => n > 0 && (n & (n - 1)) === 0;

const popcount = (n) => {
  let bits = n >>> 0;               // unsigned, so negatives count all 32
  let count = 0;
  while (bits) {
    count += bits & 1;
    bits >>>= 1;
  }
  return count;
};

const xorSwap = (a, b) => {
  a ^= b;
  b ^= a;
  a ^= b;
  return [a, b];
};

// Permission flags, the one place bitwise code reads well.
const READ = 1;
const WRITE = 2;
const ADMIN = 4;
const grant = READ | ADMIN;
const can = (flags, flag) => (flags & flag) !== 0;

console.log('5 & 3, 5 | 3, 5 ^ 3 :', 5 & 3, 5 | 3, 5 ^ 3);
console.log('~5, 5 << 1, 5 >> 1  :', ~5, 5 << 1, 5 >> 1);
console.log('-1 >> 0 vs -1 >>> 0 :', -1 >> 0, -1 >>> 0);
console.log('1 << 30, 31, 32     :', 1 << 30, 1 << 31, 1 << 32);
console.log('2 ** 31 | 0         :', 2 ** 31 | 0, 'and 2 ** 32 | 0:', 2 ** 32 | 0);
console.log('~~3.7, ~~-3.7       :', ~~3.7, ~~-3.7);
console.log('powers of two       :', [1, 2, 3, 4, 1024, 0, -4].map(isPowerOfTwo));
console.log('popcount            :', popcount(255), popcount(1024), popcount(-1));
console.log('grant               :', grant, can(grant, READ), can(grant, WRITE), can(grant, ADMIN));

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('the three pairwise operators on 5 and 3 give 1, 7 and 6', [5 & 3, 5 | 3, 5 ^ 3], [1, 7, 6]);
test('~n is -(n + 1), and ~~x truncates towards zero', [~5, ~~3.7, ~~-3.7], [-6, 3, -3]);
test('>> keeps the sign bit, >>> does not, so -1 becomes 4294967295', [-1 >> 0, -1 >>> 0], [-1, 4294967295]);
test('shifting left doubles until bit 31, then it goes negative and wraps', [1 << 30, 1 << 31, 1 << 32], [1073741824, -2147483648, 1]);
test('the same wall shows up in | 0: 2 ** 31 is negative and 2 ** 32 is zero', [2 ** 31 | 0, 2 ** 32 | 0], [-2147483648, 0]);
test('n & (n - 1) clears the lowest bit, so the test needs the n > 0 guard', [1, 2, 3, 4, 1024, 0, -4].map(isPowerOfTwo), [true, true, false, true, true, false, false]);
test('popcount over the unsigned view: 255 has 8 bits and -1 has all 32', [popcount(255), popcount(1024), popcount(-1)], [8, 1, 32]);
test('three xors swap two numbers with no third variable', xorSwap(9, 4), [4, 9]);
test('flags read well: read and admin granted, write withheld', [grant, can(grant, READ), can(grant, WRITE), can(grant, ADMIN)], [5, true, false, true]);

Every bitwise operator converts its operands to a signed 32-bit integer, does the work, and converts back to a double. That conversion is the whole story. 1 << 31 sets the sign bit, so it reads as -2147483648. 1 << 32 is 1, because the shift count is taken modulo 32 and a shift of 0 does nothing. -1 >>> 0 is 4294967295, the same 32 bits reinterpreted as unsigned.

None of that is a defect, but it means bitwise code silently caps out at about two billion. popcount above uses >>> 0 on purpose, so a negative input is counted over its two's complement form and popcount(-1) is 32 rather than an infinite loop. isPowerOfTwo needs the n > 0 guard because 0 & -1 is 0 and would otherwise call zero a power of two.

The xor swap is a party trick, not advice: [a, b] = [b, a] is clearer and no slower. Flags are the case where bitwise code earns its place — a single number carries a set, | adds, & tests, and everything fits in one word.

Common mistakes

  • Using bitwise tricks on large numbers. Anything past 2147483647 wraps. ~~3000000000 is not 3000000000.
  • Using >> in a bit-counting loop. For negative numbers it never reaches 0. Use >>>.
  • Forgetting n > 0 in the power-of-two test. 0 & -1 is 0, so zero would pass.

Try it yourself

  1. Add an EXPORT flag worth 8. Grant READ | EXPORT and check every flag.
  2. Write revoke(flags, flag) that turns one flag off. (Hint: & ~flag.)
  3. Write isBitSet(n, i) that tells you whether bit number i of n is 1, using >> and & 1.

Keep practising

Newsletter

New writing, when it lands.

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