In JavaScript, all integer numeric variables are signed by default, what does that mean?
A signed integer uses a 31-bit numeric value that represents an integer, a symbol with a 32nd digit integer, 0 for a positive number, and a 1 for negative numbers.
The range of values ranges from -2^31-2^31-1 2147483648 to 2147483647.
When JavaScript is bit-operated, a 32-bit signed integer is used, which means that the result of the conversion is also a 32-bit signed integer. In some cases, we will have unexpected results of the shift, the following is the C language and JS contrast.
C language
Copy Code code as follows:
unsigned int a = 3774191835u;
unsigned int b = a >> 2;
/* b = = 943547958 * *
Javascript
Copy Code code as follows:
var a = 3774191835;
var B = a >> 2;
/* b = = 130193866 */
As you can see, JavaScript is a signed integer when it is used for bit operations, so we get a different result. How to solve it?
We can convert the number of symbols in JavaScript into unsigned numbers. Just need to do >>>0 shift operation is good.
It is best not to use >>, recommended >>> because the leftmost one will be resolved into a sign bit, when the number overflows, will be resolved into negative numbers.