JS: BigInt .asIntN .asUintN

By Xah Lee. Date: . Last updated: .

BigInt.asIntN

// convert to 64-bit signed integer
console.log( BigInt.asIntN(64, 12345678901234567890n) )
// -6101065172474983726n

BigInt.asUintN

// convert to 64-bit unsigned integer
console.log( BigInt.asUintN(64, 12345678901234567890n) )
// 12345678901234567890n

what is JavaScript BigInt .asIntN for

what is JavaScript BigInt .asIntN for

ai answer

BigInt.asIntN(bits, bigint) is a static method on the BigInt constructor that truncates a BigInt value to the given number of least significant bits and returns the result interpreted as a signed integer (using two’s complement).

Syntax

BigInt.asIntN(bits, bigint)

Returns: bigint modulo (2^{\text{bits}}), interpreted as a signed integer in the range ([-2^{\text{bits}-1}, 2^{\text{bits}-1}-1]).

Throws: RangeError if bits is negative or larger than (2^{53}-1).

How it works

It keeps only the lowest bits bits of the value. If the highest of those remaining bits is 1, the result is treated as negative (two’s complement).

Examples (from MDN):

// 25n in binary is 00011001
BigInt.asIntN(3, 25n);  // 1n   (lowest 3 bits: 001)
BigInt.asIntN(4, 25n);  // -7n  (lowest 4 bits: 1001 → signed)

// Useful for staying in fixed-width signed ranges (e.g. 64-bit)
const max = 2n ** (64n - 1n) - 1n;   // 9223372036854775807n

BigInt.asIntN(64, max);       // 9223372036854775807n
BigInt.asIntN(64, max + 1n);  // -9223372036854775808n  (overflow wraps)

Common uses

There is a companion method BigInt.asUintN(bits, bigint) that does the same thing but interprets the result as an unsigned integer.