I really don’t want to say anything. MDN

>> (with sign moved right)

We know that computers store numbers in binary, and the leftmost digit in the binary is called a sign bit, so it’s obvious that if you move 2 bits to the right, the leftmost digit is missing 2 bits, you should fill the number, and what? I’ll fill in whatever the sign bit is, so the leftmost two bits in -9 >> 2 are the same as the sign bit, which is 1.

>>> (unsigned right shift)

So zero-fill is a little bit more obvious, just say, zero fill, so if I move it to the right and the space is empty whatever your sign bit is, I’m just going to fill it with zero.

conclusion

So what we mean by signed and unsigned is the binary sign bit, unsigned: we don’t care about the sign bit, move it right and fill it with 0; There’s a sign, so WHATEVER the sign bit is, I’m going to fill it in, same thing in Java.

background

As a front end, what does this bit breaker do? Because recently I saw a binary article, very interesting. In LeetCode 69, there is a hole in the bit operation for mid:

Topic:

Unsigned right shift can pass

var mySqrt = function(x) {
  let left = 0,
    right = x;

  while (left < right) {
    const mid = left + right + 1 >>> 1;
    if (mid * mid > x) {
      right = mid - 1;
    } else{ left = mid; }}return left;
};
Copy the code

But it doesn’t work if you have a sign to the right, so you can try that

The reason is that it will be stuck in the case of 2147483647. Do you want to know why? (The fun begins.)

We can find 2147483647 binary is 1111111111111111111111111111111 (1) a total of 31 here, I have left + right + 1 operation, Namely 0 + 2147483647 + 1 that the value of binary is 10000000000000000000000000000000 (32)

Learn c + + classmates will find some questions, c + + int is 32 bit, the left one is the sign bit, so you this overflow ah, after you are > > operation, so after moves to the right will become 11000000000000000000000000000000 (32)

But what does this have to do with my JS? What are you C++ talking about? My JS number is 64 – bit double – precision floating – point number, the value of the big to go!

But it does matter, because when JS does a bit operation, it will be converted to a 32-bit integer before it does a bit operation. So should that sentence: JS do bit operation, not fast.

So when you get to 0 plus 2147483647 plus 1, the calculation is already wrong, and it’s a negative number. I’ll believe it if you say it’s a negative number. You’re so bad, I believe you!

But check it out for yourself. You don’t even want to believe it.

Welcome to the public account “one front end”

I will regularly share some learning and summary, and make progress together with everyone