BigInt.asIntN()

Baseline 已广泛支持

此功能已成熟,并可在许多设备和浏览器版本上使用。自 2020 年 9 月起,所有浏览器均已提供此功能。

BigInt.asIntN() 静态方法会将 BigInt 值截断为指定的最低有效比特数,并以带符号整数的形式返回该值。

试一试

const I64_CEIL = 2n ** 63n;

console.log(BigInt.asIntN(64, I64_CEIL - 1n));
// 9223372036854775807n (2n ** 64n - 1n, the maximum non-wrapping value)
console.log(BigInt.asIntN(64, I64_CEIL));
// -9223372036854775808n (wraps to min value)
console.log(BigInt.asIntN(64, I64_CEIL + 1n));
// -9223372036854775807n (min value + 1n)
console.log(BigInt.asIntN(64, I64_CEIL * 2n));
// 0n (wrapped around to zero)
console.log(BigInt.asIntN(64, -I64_CEIL * -42n));
// 0n (also wraps on negative multiples)

语法

js
BigInt.asIntN(bits, bigint)

参数

bits

返回的 BigInt 可用的比特数。应为介于 0 和 253 - 1 之间(包含)的整数。

bigint

要截断以适应所提供比特数的 BigInt 值。

返回值

bigint2 ** bits 取模后的值,以带符号整数形式表示。

异常

RangeError

如果 bits 为负数或大于 253 - 1,则抛出此错误。

描述

BigInt.asIntN 方法会将 BigInt 值截断为指定的比特数,并将结果解释为带符号整数。例如,对于 BigInt.asIntN(3, 25n),值 25n 被截断为 1n

25n = 00011001 (base 2)
          ^=== Use only the three remaining bits
===>       001 (base 2) = 1n

如果剩余数字的最高有效比特是 1,则结果为负数。例如,BigInt.asIntN(4, 25n) 得到 -7n,因为在二进制补码表示中,1001-7 的编码。

25n = 00011001 (base 2)
         ^==== Use only the four remaining bits
===>      1001 (base 2) = -7n

注意: BigInt 值在二进制中始终编码为二进制补码。

与诸如 Number.prototype.toExponential() 等类似的语言 API 不同,asIntNBigInt 的一个静态属性,因此您始终将其用作 BigInt.asIntN(),而不是作为 BigInt 值的某个方法。将 asIntN() 作为“标准库函数”暴露出来,可以实现与 asm.js 的互操作

示例

保持在 64 位范围内

BigInt.asIntN() 方法有助于保持在 64 位算术范围内。

js
const max = 2n ** (64n - 1n) - 1n;

BigInt.asIntN(64, max); // 9223372036854775807n

BigInt.asIntN(64, max + 1n); // -9223372036854775808n
// negative because the 64th bit of 2^63 is 1

规范

规范
ECMAScript® 2026 语言规范
# sec-bigint.asintn

浏览器兼容性

另见