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

瀏覽器相容性

另見