JavaScript 32-bit integer unsigned operation example _javascript tips

Source: Internet
Author: User
Tags numeric value
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.
Related Article

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.