1 <<-1
1 <<-1 What is the number?
Literally 1 left-1 bit, it seems to be 1 right move 1 bit meaning.
But the actual result is 2147483648, and 2147483648 =-2 31.
Which means that actually 1 << 1 is equivalent to:
1 << 31
Why? ╯_╰ ╭ There is no why, it is so defined, it can be said that in order to match the JavaScript in the integral type is 32-bit.
That is to say M << n equals:
M << (-n% 32 + 32)
In C, this is the wrong way to write a compilation.
However, the result of this formula in Java is the same as in JavaScript. It is precisely when the arithmetic number is 32-digit shaping. For example, if we change the numbers to grow and reshape, the results are different.
public class test{public
static void Main (string[] args) {
System.out.println (1L <<-1); -9223372036854775808
}
}
So, what about 1 >> 1?
The left-shifted negative digits appear to be fixed to 0.
No matter which number to move, the number of shifts is the same.
Alert (1 >>-1)//0
(1 << 31) Why are negative numbers
First, the displacement operation is based on the complement, so first review the knowledge of the complement.
The complement of a positive integer is its own.
The complement of a negative integer is that its sign bit is unchanged, and the value part is reversed, and then the whole number plus 1.
(32-bit integer-2147483648 is somewhat special, the binary representation is-10000000000000000000000000000000, and the complement is 10000000000000000000000000000000)
So the 1 complement is 00000000000000000000000000000001, and the left 31-bit becomes 10000000000000000000000000000000, or-2147483648.
(1 << 31)-1 how much?
Because 1 << 31 is a 32-bit integer that represents a minimum number of digits, the result of this expression in Java is 2147483647, which means that the overflow then becomes the largest integral that can be represented.
But JavaScript is not the same, the result of this equation is 2147483649, because the JavaScript engine automatically turns it into a 64-bit floating-point number.
A pen test
How much is -13 >> 2?
With so much talk, the problem is very simple.
Because-1310 is-11012, then the complement is 1111 .... 0011, then 2 digits to the right 1111 ... 1100. So the final result is-1002, the result is-410.
We can also remember that the right shift 1-bit operation is divided by 2 and then the next rounding.