Signed right shift with a positive number returns 0
with the following example:
console.log(10 >> 5);
If we continue infinitely doing the same thing, it will always give us 0
:
console.log(10 >> 8);
But if the number is negative when reaching the maximum divisible limit, it returns us -1
instead of zero:
console.log(-10 >> 5);
And if we do it infinitely, it will always return us -1
.
My question is... why in the last case the value returned is always -1
when the division limit is reached??, shouldn't it be 0
the same as in the case where the number is positive?
If you try with both negative numbers, the same thing happens:
console.log(-10 >> -8);
I know that it doesn't make sense that you can shift to the right in a negative way, but in this case it also continues to return -1
and not 0
or by default -10
it was the original number, why does this happen?
That is to say, I would understand that it returned -10
in case it did not make any displacement, but in this case when returning a number different from the original I feel that even so a displacement is being made.
To understand what's going on, it's a good idea to look at the numbers you're shifting in binary. To do this, let's run the following script:
Looking at the binary representation of negative numbers in
js
it is already possible to shed light on the matter, and that is that itjavascript
uses the 2's complement to represent negative numbers. Finding the 2's complement to represent a negative number in binary is easy and can be achieved:-10
absolute value it would be10
and its binary representation1010
.11111111111111111111111111110101
).11111111111111111111111111110101
+1
=11111111111111111111111111110110
)This representation causes move operations to behave differently than we might expect.
When performing the shift right operation,
javascript
inserts a 0 or a 1 to the left depending on whether the number to shift is positive or negative.If the number to be moved is positive, as many zeros will be inserted to the left as specified in the operation, eliminating the same number of digits inserted to the right of the number. The limiting case is reached when so many zeros have been inserted that all the significant figures have been cancelled, leaving the 32 bits at zero, therefore, the limiting case is zero.
In the case of negative numbers, before a shift to the right, ones are inserted to the left, and similarly, the same number of figures that were inserted from the least significant figures are eliminated. The limiting case is reached when as many ones as there are significant figures in the number have been inserted, leaving only ones, and therefore, the value -1.
In the case of numbers shifted by a negative amount, the limiting case will always occur. In this case 0 if the number to be shifted is positive, or -1 if the number is negative.