Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Number and BigInt

BigInt.asIntN() and BigInt.asUintN()

Reference for BigInt.asIntN() and asUintN(): wrap a BigInt to a signed or unsigned integer of a given bit width, with 64-bit overflow examples.

BigInt.asIntN(bits, value) and BigInt.asUintN(bits, value) take a BigInt and wrap it to fit a fixed number of bits, like the integer types in C or Rust. asIntN treats the result as signed (two's complement), so it ranges from -(2^(bits-1)) to 2^(bits-1) - 1. asUintN treats it as unsigned, from 0 to 2^bits - 1.

BigInts never overflow by themselves. These two functions are how you simulate the overflow of 8-, 16-, 32- or 64-bit integers, for hashing, binary formats and checksums.

JavaScript
BigInt.asUintN(8, 257n);   // 1n
BigInt.asIntN(8, 255n);    // -1n

Try it

JS Wrapping to 8 bits

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS 64-bit arithmetic with overflow

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
BigInt.asIntN(bits, bigint)
BigInt.asUintN(bits, bigint)
Name Description
bits The width in bits, a non-negative integer up to 2^53 - 1. A value of 0 always gives 0n.
bigint The BigInt to wrap.

Return value: a BigInt. For asIntN it is bigint modulo 2^bits, mapped into the signed range. For asUintN it is bigint modulo 2^bits, in the range 0 to 2^bits - 1.

Exceptions: a TypeError if bigint is not a BigInt (a plain number is not converted for you), and a RangeError if bits is negative or too large.

Usage notes

  • Wrap after each operation that could overflow. Doing many multiplications and wrapping only at the end gives the same result mathematically, but the intermediate values grow large and slow.
  • Signed versus unsigned is only a view of the same bits. asIntN(8, 255n) is -1n and asUintN(8, -1n) is 255n; both come from the bit pattern 11111111.
  • Negative inputs work as in two's complement, so asUintN(8, -1n) is 255n.
  • Not rounding or clamping. The functions wrap around. They do not saturate at the limits.
  • For 32-bit work with plain numbers, use |0, >>> 0 or Math.imul(), which are faster than BigInt. Use these BigInt functions when you need 64 bits or more, or other widths.
  • Typed arrays such as BigInt64Array and BigUint64Array perform the same wrapping when you store values in them.

Browser support

BigInt and these two functions are supported in all current browsers and in Node.js.