Bit shift operators in JavaScript
Advanced · 4 min read
Shifting a number's bits left or right is the binary version of adding or removing zeros at the end of a decimal number. In base 10, 5 becomes 50 when you add a zero, ten times bigger. In binary, adding a zero makes a number two times bigger. JavaScript has three shift operators: << (shift left), >> (shift right) and >>> (unsigned shift right).
Shifts are used to build bit masks, pack colors and other small values into one number, and work with binary file formats. In this tutorial you will use them to multiply and divide by powers of two, then find the places where they give a different answer from normal arithmetic. You need to know binary and the bitwise operators & and |.
Shifting, by hand
5 in binary is 101. Shift it left by 1 and a 0 joins on the right: 1010, which is 10. Shift by 3 and three zeros join: 101000, which is 40. So n << k is n times 2 to the power k.
Shifting right does the opposite: bits fall off the right-hand end. 40 is 101000. Shift it right by 3 and you get 101, which is 5. So n >> k divides by 2 to the power k, throwing away any remainder.
The 32-bit catch
All of JavaScript's bitwise operators, shifts included, first turn the number into a 32-bit signed whole number. The leftmost of those 32 bits is the sign bit: when it is 1, the number counts as negative. This is the cause of every surprise in this lesson.
Here is the exercise. Have a go yourself first if you like, then read on and we will build it together.
69 Shifts, and the count taken modulo 32
hardUse << and >> to multiply and divide by powers of two, then find the smallest multiplication they get wrong. Compare >> with >>> on a negative, and work out what 1 << 32 is.
Stuck? Three hints, smallest first
- 1.
n << kisn * 2 ** konly while the answer fits in 32 signed bits. - 2. The shift count is taken modulo 32, so a count of 32 shifts by nothing at all.
- 3.
>>copies the sign bit inwards;>>>feeds in zeroes and so is never negative.
Step 1: multiply and divide
const shiftLeft = (n, k) => n << k;
const half = (n) => n >> 1;
console.log(shiftLeft(5, 1), shiftLeft(5, 3)); // 10 40
console.log(40 >> 3, 40 >>> 3); // 5 5
console.log(half(9)); // 4
Both right shifts agree on a positive number. half(9) gives 4, because the remainder bit falls off the end.
Step 2: where shifting stops being multiplying
3 is 11. Shift it left by 30 and the top 1 lands in bit 31, the sign bit:
console.log(3 << 30); // -1073741824
console.log(3 * 2 ** 30); // 3221225472
The real answer is about 3.2 billion. The shift gives a negative number, because that top bit now says "negative". A 32-bit signed number can only go up to 2147483647, a little over 2.1 billion, and 3.2 billion doesn't fit.
So use * 2 ** k for ordinary arithmetic. Use shifts only when you really mean "work on these 32 bits", and say so in a comment.
Step 3: 1 << 31 and 1 << 32
console.log(1 << 31); // -2147483648
console.log(1 << 32, 1 << 33); // 1 2
1 << 31 sets only the sign bit, which gives the most negative 32-bit number. You might expect 1 << 32 to push the 1 off the end and give 0. It gives 1.
The reason: JavaScript only uses the bottom five bits of the shift count, which is the same as taking the count modulo 32. A count of 32 becomes 0, so nothing moves. A count of 33 becomes 1, so 1 << 33 is 2. There is no shift count that clears a value to zero.
Step 4: >> against >>> on a negative
Now the two right shifts differ. >> copies the sign bit into the gap on the left, so a negative number stays negative. >>> always fills with zeros.
console.log(-8 >> 1); // -4
console.log(-8 >>> 1); // 2147483644
-8 >> 1 is -4, half of -8, as you would hope. -8 >>> 1 reads the bits of -8 as if there were no sign, shifts them, and fills with a 0, so the result is a large positive number.
Step 5: >>> 0 as an unsigned reading
Shifting by 0 moves nothing, but >>> still reads the bits as unsigned. That makes x >>> 0 a common idiom for "show me this 32-bit pattern as a positive number":
console.log(-1 >>> 0); // 4294967295
console.log((-1 >>> 0) | 0); // -1
-1 is thirty-two 1 bits, which unsigned is 4294967295. Applying | 0 reads the same bits as signed again and gives back -1.
Step 6: >> rounds down, not toward zero
For negative odd numbers, >> and ordinary division part ways:
console.log(-7 >> 1); // -4
console.log(Math.trunc(-7 / 2)); // -3
console.log(Math.floor(-7 / 2)); // -4
-7 / 2 is -3.5. Math.trunc cuts toward zero and gives -3. >> 1 rounds down (toward minus infinity), like Math.floor, and gives -4. For positive numbers the two agree, so this only shows up with negatives.
The full solution
The answer panel has shiftLeft and half, and prints the multiplications and divisions, 3 << 30 against 3 * 2 ** 30, 1 << 31, 1 << 32 and 1 << 33, both right shifts of -8, -1 >>> 0 and back, and -7 >> 1 against trunc and floor. Press Run to see the output.
const shiftLeft = (n, k) => n << k;
const half = (n) => n >> 1;
console.log('5 << 1, 5 << 3 :', 5 << 1, 5 << 3);
console.log('40 >> 3, 40 >>> 3:', 40 >> 3, 40 >>> 3);
console.log('3 << 30 :', 3 << 30, 'but 3 * 2 ** 30 is', 3 * 2 ** 30);
console.log('1 << 31 :', 1 << 31, '<- the sign bit');
console.log('1 << 32, 1 << 33 :', 1 << 32, 1 << 33, '<- count taken mod 32');
console.log('-8 >> 1, -8 >>> 1:', -8 >> 1, -8 >>> 1);
console.log('-1 >>> 0 :', -1 >>> 0, 'and back:', (-1 >>> 0) | 0);
console.log('-7 >> 1 :', -7 >> 1, 'against trunc', Math.trunc(-7 / 2), 'and floor', Math.floor(-7 / 2));
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('shifting left multiplies by a power of two: 10 and 40', [shiftLeft(5, 1), shiftLeft(5, 3)], [10, 40]);
test('and shifting right divides, with >> and >>> agreeing on positives', [40 >> 3, 40 >>> 3], [5, 5]);
test('3 << 30 overflows into the sign bit and comes back negative', [3 << 30, 3 * 2 ** 30], [-1073741824, 3221225472]);
test('1 << 31 is the most negative 32-bit integer', 1 << 31, -2147483648);
test('the count is taken modulo 32, so 1 << 32 is 1 and 1 << 33 is 2', [1 << 32, 1 << 33], [1, 2]);
test('>> keeps the sign while >>> reads the same bits as unsigned', [-8 >> 1, -8 >>> 1], [-4, 2147483644]);
test('so -1 >>> 0 is the full 32-bit pattern, and | 0 undoes it', [-1 >>> 0, (-1 >>> 0) | 0], [4294967295, -1]);
test('>> is a floor division of a negative, not a truncation', [-7 >> 1, Math.trunc(-7 / 2), Math.floor(-7 / 2)], [-4, -3, -4]);
Shifting is only multiplication and division while the result stays inside 32 signed bits, and the boundary arrives sooner than people expect: 3 << 30 is already wrong, at about 3.2 billion. Use * 2 ** k unless you are deliberately working on a 32-bit pattern, in which case say so in a comment.
Two behaviours to keep straight. The shift count is reduced modulo 32, so 1 << 32 is 1 rather than 4294967296 and there is no shift that clears a value to zero. And >> is an arithmetic shift, filling from the sign bit, while >>> fills with zeroes — which is why -8 >>> 1 is 2147483644 and why x >>> 0 is the idiom for reading a value as an unsigned 32-bit integer. Note also that >> floors rather than truncates, so -7 >> 1 is -4 where Math.trunc(-7 / 2) is -3; the two disagree on every odd negative.
Common mistakes
- Using
<<as a fast multiply. It breaks as soon as the result passes 2147483647.3 << 30is negative. - Expecting
1 << 32to be 4294967296, or 0. The shift count is taken modulo 32, so it is 1. - Using
>>>on numbers that can be negative.-8 >>> 1is 2147483644, not -4. Use>>when the sign matters.
Try it yourself
- Print
1 << kforkfrom 0 to 32 and spot where the results turn negative and where they start again. - Pack the color channels 30, 9 and 255 into one number with
(r << 16) | (g << 8) | b, then get green back with(n >> 8) & 0xff. - Find a negative even number where
n >> 1andMath.trunc(n / 2)agree. Why do they?