Home  >  Article  >  Web Front-end  >  JavaScript 32-bit integer unsigned operation example_javascript skills

JavaScript 32-bit integer unsigned operation example_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:10:291321browse

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, with 0 representing a positive number and 1 representing 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 code The code is as follows:

unsigned int a = 3774191835u;
unsigned int b = a >> 2;
/* b == 943547958 */

JavaScript
Copy code The code is 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 perform a >>>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, and when the number overflows, it will be parsed as a negative number.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn