Example of JavaScript 32-bit integer unsigned operation
All integer values are signed integers by default. When JavaScript performs bitwise operations, 32-bit signed integers are used, which means the conversion result is also a 32-bit signed integer.
In JavaScript, all integer variables are signed integers by default. What does this mean?
A signed integer uses 31 bits to represent the value of an integer, 32nd bits to represent an integer, 0 represents a positive number, and 1 represents a negative number.
The value range is-2 ^ 31-2 ^ 31-1, that is,-2147483648 to 2147483647.
When JavaScript performs a bit operation, it uses a 32-bit signed integer, which means that the conversion result is also a 32-bit signed integer. In some cases, unexpected results may occur when we shift data. The following is a comparison between C and JS.
C Language
The Code is as follows:
Unsigned int a = 3774191835u;
Unsigned int B = a> 2;
/* B = 943547958 */
JavaScript
The Code is as follows:
Var a = 3774191835;
Var B = a> 2;
/* B =-130193866 */
We can see that the bitwise operation in JavaScript uses signed integers, so we get different results. How can this problem be solved?
We can convert the signed number in JavaScript to the unsigned number. You only need to perform the> 0 shift operation.
It is best not to use >>, it is recommended to use >>> because the leftmost digit will be parsed into a symbol bit, and when the number overflows, it will be parsed into a negative number.