Numeric calculation-bigint Beyond the JavaScript security integer limit

Source: Internet
Author: User

The basic data class number in JavaScript is a double-precision floating-point number, which can represent a maximum security range of plus or minus 9007199254740991, which is 2 of the 53 minus one, input number.max_safe_ in the browser console, respectively Integer and Number.min_safe_integer to see the corresponding Maximum/small value

Const MAX = Number.max_safe_integer;     // →9_007_199_254_740_991    // Note: For readability, I use underscores as separators to group these numbers into thousands. The digital text separator proposal is used correctly for normal JavaScript digital text. 

By adding this maximum value, you can get the expected result:

Max + 1; // →9_007_199_254_740_992?

However, if we increase it again, the result can no longer be fully represented as JavaScript Number :

Max + 2; // →9_007_199_254_740_992?

We will find the same results as max+1 and max+2. As long as we get this particular value in JavaScript, we can't tell if it's accurate. any calculation of integers (that is, from) outside the range of safe integers Number.MIN_SAFE_INTEGER Number.MAX_SAFE_INTEGER may lose precision. For this reason, we can only rely on numeric integer values within a safe range.

BigInt

BigIntis a new primitive type in JavaScript that can represent integers with arbitrary precision . BigInt Number can safely store and manipulate large integers even if it exceeds the security integer limit of javascript .

Chrome 67+ is starting to support bigint, and all of this is based on Chrome 67.

to create a BigInt , add the n suffix after the number, For example, 123 become 123n . Global BigInt(number) functions can be used to convert number to BigInt . In other words, BigInt(123) === 123n . Let's use both of these techniques to solve the problems we encountered before:

BigInt (Number.max_safe_integer) + 2n; // →9_007_199_254_740_993n?

we will be two Number multiply:

1234567890123456789 * 123; // →151851850485185200000?

Look at the above two numbers, the end is 9 and 3,9*3=27, but the end of the result is 000, obviously wrong, let us use BigInt instead:

1234567890123456789n * 123n; // →151851850485185185047n?

This time we got the right result.

Numberthe security integer limit does not apply to . BigInt Therefore, BigInt We can perform the correct integer operation without worrying about losing precision.

BigIntis an original type in the JavaScript language. Therefore, you can use the typeof operator to detect this type :

typeof 123; // → ' number ' typeof 123n; // → ' bigint '

because BigInt S is a separate type, so a BigInt never equals a Number . , such as 42n !== 42 . to compare a BigInt and a Number , before comparing one of the Convert to another type or use abstract equal ( == ):

42n = = BigInt ($); // →true42n = =; // →true

when cast to a Boolean type (using the if , && , || , or Boolean(int) ), BigInt follow the same logical transformation as number .

if (0n) {  Console.log (' if 'else  {  console.log (' Else ');} // →logs ' Else ', because ' 0n ' is falsy.
Operator

BigInt supports the most common operators, the two-tuple operator + 、-、 *, * *,/,% are working correctly, bitwise operations,, | & << ,>>和Number是一样的

(7 + 6-5) * 4 * * 3/2% 3; // →1 (7n + 6n-5n) * 4n * * 3n/2n% 3n; // →1n

Unary operators - can be used to represent a negative value BigInt , such as -42n . unary + is not supported because it destroys the Asm.js code and +x always throws an exception in Asm.js .

Another problem is that it is not allowed to BigInt and the Number mixed operations between. Take a look at This example:

BigInt (Number.max_safe_integer) + 2.5; // →????

What should be the result? There's no good answer here. BigInt You cannot represent decimals and Number cannot represent BigInt numbers that exceed a safe integer limit. Therefore, BigInt Number the blending operation between and cause TypeError exception.

The only exception to this rule is the comparison operator, such as === (as previously mentioned) < , and >= -because they return a Boolean value, there is no risk of precision loss.

1 + 1n; // →typeerror123 < 124n; // →true
Api

Global BigInt Constructors and Constructors Number类似 : Converts its arguments to BigInt (as mentioned earlier). If the conversion fails, it throws one SyntaxError or RangeError exception.

BIGINT (123); // →123n BigInt (1.5); // →rangeerror BigInt (' 1.5 '); // →syntaxerror

Two library functions enable the BigInt The value is encapsulated as a signed or unsigned integer, limited to a specific number of digits. BigInt.asIntN(width, value) wrap a BigInt value as one width - Digit a binary signed integer and BigInt.asUintN(width, value) wraps a BigInt value as a width -digit binary unsigned integer. For example, if you are performing 64-bit arithmetic, you can use these APIs to maintain the appropriate scope:

// highest possible BigInt value that can be represented as a // signed 64-bit Integer. Const MAX = 2n * * (64n-1n)- 1n; BIGINT.ASINTN (max), →9223372036854775807NBIGINT.ASINTN (max + 1n); // →-9223372036854775808n //    ^ Negative because of overflow

Please note that as soon as we pass BigInt anoverflow occurs when a value exceeding a 64-bit integer range (for example, an absolute value of 63 bits + sign is 1 bits) .

BigIntyou can accurately represent 64-bit signed and unsigned integers, which are commonly used in other programming languages. Two new types of array styles, and it 's easier to BigInt64Array BigUint64Array effectively represent and manipulate the list of these values:

New Bigint64array (4); // →[0n, 0n, 0n, 0n] view.length; // →4view[0]; // →0nview[0] = 42n;view[0]; // →42n

BigInt64ArrayMake sure its value is 64-bit signed.

// highest possible BigInt value that can be represented as a // signed 64-bit Integer. Const MAX = 2n * * (64n-1n)- 1n;view[0] = max;view[0]; // →9_223_372_036_854_775_807nView[0] = max + 1n;view[0]; // →-9_223_372_036_854_775_808n //    ^ Negative because of overflow

BigUint64Array确保这些值是64-bit unsigned.

Numeric calculation-bigint Beyond the JavaScript security integer limit

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.