Chris Middleton
Chris Middleton

Reputation: 5934

Why doesn't a >>> 100 produce 0 in JavaScript?

So I was playing around with shifts in the console, and the results have me stumped.

Input:

a = -1
a >>> 100

Output:

268435455

I looked on the Mozilla reference page about it, but it mentions nothing about the behavior of >>> when you shift by large amounts. I assumed that shifting all the bits to the right with zero-fill would result in a zero.

Is this a bug in Firefox or something?

Upvotes: 2

Views: 111

Answers (2)

alex
alex

Reputation: 490303

Any bitwise operator on a Number in JavaScript will convert its operand to a 32 bit big-endian signed number.

This means that if the number is larger than what can be stored by 32 bits, it will be truncated. Big-endian means that number are stored in natural order when reading it from left to right, i.e. more significant numbers are stored first, so if the number is stored over one byte, its first byte is the more significant.

This means that -1's binary representation will be...

11111111 11111111 11111111 11111111

(This is -1 in two's complement. This is performed by calculating the number's value in binary, and then flipping each bit and adding one.)

When you shift by 100, you will find it only shifts by 4, leaving you with...

00001111 11111111 11111111 11111111

As you can see, the high bit is no longer set, so it's not negative, and it is in fact 268435455 (the number from your question).

Upvotes: 1

david
david

Reputation: 18268

It seems you can only shift by a maximum of 31.

From the site you linked in your post (MDN):

Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off, and shifting in zeros from the left.

From the actual spec (Page 77)

Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.

What's actually happening is when you shift by 100 it shifts by (100 & 0x1F) or 4.

-1 >>> 100 === -1 >>> 4

If you were to split it up into multiple shifts then it will work:

-1 >>> 25 >>> 25 >>> 25 >>> 25 === 0

Upvotes: 3

Related Questions