BigInt.asUintN()
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)
引數
返回值
bigint 對 2 ** 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 不同,asUintN 是 BigInt 的靜態屬性,因此您始終將其用作 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 |
瀏覽器相容性
載入中…