Example of JavaScript 32-bit integer unsigned operation

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.