2

I understand what is Zero-fill right shift and results it yields make perfect sense when second operand is non-zero:

-7 >>> 1
2147483644

Compare with

-7 >> 1
-4

But when second operand is zero:

-7 >> 0
-7 // Looks right!
-7 >>> 0
4294967289 // What? Why?

If I'm shifting zero bits, doesn't it mean I'm not shifting at all? If that's the case, shouldn't it give me back the original number? I would expect -7 >>> 0 === -7

And also

-7 >>> 32
4294967289

Again, by definition, I would expect -7 >>> n === 0 where n >= 32 because all digits become zeros!

Boyang
  • 2,520
  • 5
  • 31
  • 49

1 Answers1

3

Found the internal workings of it in specs.

x >>> 0 will do ToUint32(x)

And

7.1.6 ToUint32 ( argument )

The abstract operation ToUint32 converts argument to one of 232 integer values in the range 0 through 232−1, inclusive. This abstract operation functions as follows: Let number be ToNumber(argument). ReturnIfAbrupt(number). If number is NaN, +0, −0, +∞, or −∞, return +0. Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(number)). Let int32bit be int modulo 232. Return int32bit.

Note Let int32bit be int modulo, and

The notation “x modulo y” (y must be finite and nonzero) computes a value k of the same sign as y (or zero) such that abs(k) < abs(y) and x−k = q × y for some integer q.

So by above convention, -7 mod 2^32 === 2^32 - 7 === 4294967289

Boyang
  • 2,520
  • 5
  • 31
  • 49