Sub topic 13
64-Bit Integers with BigInt Typed Arrays
This chapter assumes you already know how typed arrays wrap out-of-range values, how byteOffset alignment works, and how DataView handles byte order. You should also know the basics of JavaScript's BigInt type: literals such as 10n, and the rule that you cannot mix BigInt and Number in arithmetic.
Why Number Is Not Enough
A JavaScript Number is a 64-bit IEEE 754 float. It holds integers exactly only up to Number.MAX_SAFE_INTEGER, which is 2^53 − 1. Past that point, neighbouring integers collapse into the same value.
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(2 ** 53 === 2 ** 53 + 1); // true
const f = new Float64Array([2 ** 53 + 1]);
console.log(f[0]); // 9007199254740992Many binary formats store full 64-bit integers. Common examples are nanosecond timestamps, database row IDs, file sizes and offsets in large archives, hash values, and the i64 type in WebAssembly. A Float64Array cannot hold these exactly, and no 32-bit type is wide enough. BigInt64Array and BigUint64Array fill this gap. Each element is stored as 8 raw bytes and read back as a BigInt, so you never lose precision.
The Two Types
| Type | Bytes per element | Range | Value read back |
|---|---|---|---|
| `BigInt64Array` | 8 | −2^63 to 2^63 − 1 | BigInt |
| `BigUint64Array` | 8 | 0 to 2^64 − 1 | BigInt |
They follow the same rules as every other typed array. They can own a new buffer or view an existing one. They have length, byteOffset, subarray, slice, and the rest of the methods. A view on an existing buffer needs a byteOffset that is a multiple of 8.
const buf = new ArrayBuffer(24);
const ids = new BigUint64Array(buf, 8, 2);
console.log(BigUint64Array.BYTES_PER_ELEMENT, ids.byteOffset, ids.length); // 8 8 2
try {
new BigInt64Array(buf, 4);
} catch (e) {
console.log(e instanceof RangeError); // true: 4 is not a multiple of 8
}Writing Values: BigInt In, BigInt Out
Every other typed array converts the value you write with ToNumber. The BigInt types use ToBigInt instead. That one change causes most of the surprises in this chapter.
const big = new BigInt64Array(3);
big[0] = 42n; // fine
big[1] = true; // stored as 1n
big[2] = '123'; // strings are parsed: 123n
try {
big[0] = 1; // Number, not BigInt
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(big[0], big[1], big[2]); // 42n 1n 123nPlain arrays of Numbers fail for the same reason. The length argument is still a Number, though, because it is a count and not an element value.
const a = new BigInt64Array(4); // OK: length 4, filled with 0n
const b = new BigInt64Array([1n, 2n]); // OK
try {
new BigInt64Array([1, 2]); // elements are Numbers
} catch (e) {
console.log(e instanceof TypeError); // true
}
const c = BigInt64Array.from([1, 2, 3], BigInt); // convert while copying
console.log(c[2]); // 3nWrapping
Out-of-range BigInts wrap to 64 bits, the same way Int8Array wraps to 8 bits. Writing to a BigInt64Array gives the result of BigInt.asIntN(64, x), and writing to a BigUint64Array gives BigInt.asUintN(64, x). Nothing is clamped and no error is thrown.
const s = new BigInt64Array(2);
s[0] = 2n ** 63n; // one past the max
s[1] = 2n ** 64n + 5n;
console.log(s[0], s[1]); // -9223372036854775808n 5n
const u = new BigUint64Array(1);
u[0] = -1n;
console.log(u[0]); // 18446744073709551615nThere is no clamped 64-bit type. If you need saturation, compare against the limits yourself before writing.
No Mixing with Number-Based Arrays
The spec divides typed arrays into two content types, Number and BigInt. Copying between the two groups throws, even when every value would fit.
const small = new Int32Array([1, 2]);
const wide = new BigInt64Array(2);
try {
wide.set(small);
} catch (e) {
console.log(e instanceof TypeError); // true
}
try {
new BigInt64Array(small);
} catch (e) {
console.log(e instanceof TypeError); // true
}
wide.set(Array.from(small, BigInt)); // convert explicitly
console.log(wide[1]); // 2nGoing the other way works the same: Float64Array.from(wide, Number). Use it only when you know the values are within the safe range.
Reading 64-Bit Fields with DataView
DataView has four 64-bit methods: getBigInt64, setBigInt64, getBigUint64, and setBigUint64. Like the other DataView methods, they default to big-endian and accept any byte offset. They also require BigInt values, so setBigUint64(0, 5) throws a TypeError.
const dv = new DataView(new ArrayBuffer(8));
dv.setBigUint64(0, 0x0102030405060708n); // big-endian
console.log(dv.getUint8(0)); // 1
console.log(dv.getBigUint64(0).toString(16)); // "102030405060708"
console.log(dv.getBigUint64(0, true).toString(16)); // "807060504030201"The last line shows the usual byte-order bug at full width. All eight bytes come back reversed, and the result looks like a valid number, so nothing warns you.
Here is a record that holds a 64-bit timestamp after a 2-byte header. The timestamp starts at offset 2, so it is unaligned. A BigUint64Array view cannot start there, but DataView can read it.
// Layout: uint16 type (LE), uint64 timestampNs (LE)
function parseEvent(buffer) {
const dv = new DataView(buffer);
return {
type: dv.getUint16(0, true),
timestampNs: dv.getBigUint64(2, true),
};
}
const buf = new ArrayBuffer(10);
const w = new DataView(buf);
w.setUint16(0, 7, true);
w.setBigUint64(2, 1732528668674000000n, true);
const ev = parseEvent(buf);
console.log(ev.type, ev.timestampNs); // 7 1732528668674000000nWorking with the Values You Read
Once you have BigInts, the BigInt rules apply, and several familiar habits break.
Arithmetic and Reductions
You cannot mix BigInt and Number in arithmetic. A reduce with initial value 0 throws on the first addition. Use 0n.
const sizes = new BigUint64Array([10n, 20n, 30n]);
console.log(sizes.reduce((sum, x) => sum + x, 0n)); // 60n
try {
sizes.reduce((sum, x) => sum + x, 0);
} catch (e) {
console.log(e instanceof TypeError); // true
}Math.max, Math.min, and the rest of Math do not accept BigInt either. Use loops or reduce with > and <, which compare BigInts correctly.
Sorting
The default sort() sorts BigInt typed arrays numerically. A custom comparator must return a Number. The common (a, b) => a - b returns a BigInt, which throws.
const v = new BigInt64Array([3n, -1n, 2n]);
v.sort();
console.log(v[0], v[1], v[2]); // -1n 2n 3n
try {
v.sort((a, b) => a - b);
} catch (e) {
console.log(e instanceof TypeError); // true
}
v.sort((a, b) => (a < b ? 1 : a > b ? -1 : 0)); // descending, returns Numbers
console.log(v[0]); // 3nConverting to Number and JSON
Number(big) never throws. It rounds quietly when the value is outside the safe range. If a value has to become a Number, check it first:
function toSafeNumber(b) {
if (b > BigInt(Number.MAX_SAFE_INTEGER) || b < BigInt(Number.MIN_SAFE_INTEGER)) {
throw new RangeError(`${b} cannot be represented exactly as a Number`);
}
return Number(b);
}
console.log(toSafeNumber(1234n)); // 1234JSON.stringify throws a TypeError on BigInt values. Pass a replacer that turns them into strings, which is also what most APIs expect for 64-bit IDs:
const record = { id: new BigUint64Array([2n ** 60n])[0] };
const json = JSON.stringify(record, (k, val) =>
typeof val === 'bigint' ? val.toString() : val
);
console.log(json); // {"id":"1152921504606846976"}Splitting into 32-Bit Halves
Some APIs and older code paths work only with 32-bit Numbers. You can split an unsigned 64-bit value into high and low words with shifts and masks, and join them back the same way:
function splitU64(b) {
return { hi: Number(b >> 32n), lo: Number(b & 0xffffffffn) };
}
function joinU64(hi, lo) {
return (BigInt(hi >>> 0) << 32n) | BigInt(lo >>> 0);
}
const { hi, lo } = splitU64(0x0123456789abcdefn);
console.log(hi.toString(16), lo.toString(16)); // "1234567" "89abcdef"
console.log(joinU64(hi, lo).toString(16)); // "123456789abcdef"The >>> 0 makes sure each half is treated as unsigned, even if a caller passes a negative Int32.
Cost and When to Use Them
Every element you read from a BigInt typed array creates a BigInt value. In hot loops this is slower than reading from Float64Array or Int32Array, and engines optimize it less. Use these types when you need exact 64-bit values. Avoid them when the values always fit in 53 bits and you plan to convert to Number right away.
| Situation | Good choice |
|---|---|
| Exact 64-bit IDs, hashes, nanosecond times | `BigUint64Array` / `BigInt64Array` |
| Unaligned 64-bit field inside a record | `DataView.getBigUint64` / `getBigInt64` |
| Values always below 2^53, heavy arithmetic | `Float64Array` |
| WebAssembly `i64` memory | `BigInt64Array` over `memory.buffer` |
Exercise
What does this code print, and why? const u = new BigUint64Array(2); u[0] = 2n ** 64n - 1n; u[1] = u[0] + 2n; console.log(u[0], u[1]);
Show answer
It prints 18446744073709551615n 1n. The first value is the largest unsigned 64-bit integer, so it fits. The sum 2n ** 64n + 1n is computed exactly as a BigInt, then wrapped modulo 2^64 when stored, which leaves 1n.
Exercise
A colleague writes const totals = new BigInt64Array(counts) where counts is an Int32Array, and it throws. Why, and what is the fix?
Show answer
Int32Array has the Number content type and BigInt64Array has the BigInt content type, and the constructor refuses to copy between them, so it throws a TypeError. Convert explicitly instead: BigInt64Array.from(counts, BigInt).
Exercise
A file header stores a little-endian unsigned 64-bit length at byte offset 4. Write one expression that reads it from an ArrayBuffer named buf, and explain why new BigUint64Array(buf, 4, 1) is not an option.
Show answer
new DataView(buf).getBigUint64(4, true). A BigUint64Array view needs a byteOffset that is a multiple of 8, so offset 4 throws a RangeError. The view would also use the platform's byte order instead of guaranteeing little-endian.