BigInt.asUintN()

Baseline 已广泛支持

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

BigInt.asUintN() 静态方法将一个 BigInt 值截断为指定的最低有效位数,并将其作为无符号整数返回。

试一试

const U64_CEIL = 2n ** 64n;

console.log(BigInt.asUintN(64, U64_CEIL - 1n));
// 18446744073709551615n (2n ** 64n - 1n, the maximum non-wrapping value)
console.log(BigInt.asUintN(64, U64_CEIL));
// 0n (wraps to zero)
console.log(BigInt.asUintN(64, U64_CEIL + 1n));
// 1n
console.log(BigInt.asUintN(64, U64_CEIL * 2n));
// 0n (wraps on multiples)
console.log(BigInt.asUintN(64, U64_CEIL * -42n));
// 0n (also wraps on negative multiples)

语法

js
BigInt.asUintN(bits, bigint)

参数

bits

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

bigint

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

返回值

bigint2 ** bits 取模的值,作为无符号整数。

异常

RangeError

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

描述

BigInt.asUintN 方法将 BigInt 值截断为指定的位数,并将结果解释为无符号整数。无符号整数没有符号位,始终为非负数。例如,对于 BigInt.asUintN(4, 25n),值 25n 被截断为 9n

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

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

与 类似 Number.prototype.toExponential() 的语言 API 不同,asUintNBigInt 的静态属性,因此您始终将其用作 BigInt.asUintN(),而不是 BigInt 值的方法。将 asUintN() 公开为“标准库函数”可以 与 asm.js 进行互操作

示例

保持在 64 位范围内

BigInt.asUintN() 方法可用于保持在 64 位算术范围内。

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

BigInt.asUintN(64, max); // 18446744073709551615n

BigInt.asUintN(64, max + 1n); // 0n
// zero because of overflow: the lowest 64 bits are all zeros

规范

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

浏览器兼容性

另见