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 BigInt.asIntN()
statische Methode kürzt einen BigInt
-Wert auf die angegebene Anzahl der niederwertigsten Bits und gibt diesen Wert als vorzeichenbehaftete Ganzzahl 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 Ganzzahl.
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 angegebenen Bits und interpretiert das Ergebnis als vorzeichenbehaftete Ganzzahl. 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
, da 1001
die Kodierung von -7
im Zweierkomplement darstellt:
25n = 00011001 (base 2) ^==== Use only the four remaining bits ===> 1001 (base 2) = -7n
Note:
BigInt
-Werte werden immer im Binärformat als Zweierkomplement kodiert.
Anders als bei ähnlichen API-Funktionen wie Number.prototype.toExponential()
ist asIntN
eine statische Eigenschaft von BigInt
, daher wird sie immer als BigInt.asIntN()
verwendet und nicht als Methode eines BigInt-Wertes. Die Bereitstellung von asIntN()
als "Standardbibliotheksfunktion" ermöglicht die Interoperabilität mit asm.js.
Beispiele
Innerhalb von 64-Bit-Bereichen 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® 2025 Language Specification # sec-bigint.asintn |
Browser-Kompatibilität
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
asIntN |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support