BigInt.asIntN()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.
Die statische Methode BigInt.asIntN()
kürzt einen BigInt
-Wert auf die angegebene Anzahl der niederwertigsten Bits und gibt diesen Wert als vorzeichenbehaftete ganze Zahl zurück.
Probieren Sie es aus
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)
Syntax
BigInt.asIntN(bits, bigint)
Parameter
Rückgabewert
Der Wert von bigint
modulo 2 ** bits
, als vorzeichenbehaftete ganze Zahl.
Ausnahmen
RangeError
-
Wird ausgelöst, wenn
bits
negativ ist oder größer als 253 - 1.
Beschreibung
Die Methode BigInt.asIntN
kürzt einen BigInt
-Wert auf die gegebene Anzahl an Bits und interpretiert das Ergebnis als vorzeichenbehaftete ganze Zahl. Zum Beispiel wird bei BigInt.asIntN(3, 25n)
der Wert 25n
auf 1n
gekürzt:
25n = 00011001 (base 2) ^=== Use only the three remaining bits ===> 001 (base 2) = 1n
Wenn das führende Bit der verbleibenden Zahl 1
ist, ist das Ergebnis negativ. Zum Beispiel ergibt BigInt.asIntN(4, 25n)
-7n
, weil 1001
die Kodierung von -7
im Zweierkomplement ist:
25n = 00011001 (base 2) ^==== Use only the four remaining bits ===> 1001 (base 2) = -7n
Note:
BigInt
-Werte sind immer im Zweierkomplement im Binärformat kodiert.
Anders als bei ähnlichen APIs wie Number.prototype.toExponential()
, ist asIntN
eine statische Eigenschaft von BigInt
, sodass Sie es immer als BigInt.asIntN()
und nicht als Methode eines BigInt-Wertes verwenden. Die Bereitstellung von asIntN()
als "Standardbibliotheksfunktion" ermöglicht die Interoperabilität mit asm.js.
Beispiele
Im 64-Bit-Bereich bleiben
Die Methode BigInt.asIntN()
kann nützlich sein, um innerhalb des Bereichs der 64-Bit-Arithmetik zu bleiben.
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
Spezifikationen
Specification |
---|
ECMAScript® 2026 Language Specification # sec-bigint.asintn |