In JavaScript, all integer variables are signed integers by default. What does this mean?
Signed integers use 31 bits to represent the value of the integer, and bit 32 to represent the sign of the integer. 0 represents a positive number, and 1 represents a negative number.
The value range is from -2^31 - 2^31-1, which is -2147483648 to 2147483647.
When JavaScript performs bit operations, it uses a 32-bit signed integer type, which means that the result of the conversion is also a 32-bit signed integer type. Sometimes, unexpected results will occur when we perform shifting. The following is a comparison between C language and JS.
C language
Copy the code code as follows:
unsigned int a = 3774191835u;
unsigned int b = a >> 2;
/* b == 943547958 */
JavaScript
Copy the code code as follows:
var a = 3774191835;
var b = a >> 2;
/* b == -130193866 */
As you can see, JavaScript uses signed integers when performing bit operations, so we get different results. How to solve it?
We can convert signed numbers in JavaScript into unsigned numbers. Just do the >>>0 shift operation.
It is best not to use >>. It is recommended to use >>> because the leftmost bit will be parsed as a sign bit. When the number overflows, it will be parsed as a negative number.