← 中文资源

简体中文版本

用 BigInt64Array 精确存储 64 位整数

用 BigInt64Array 存储超出 MAX_SAFE_INTEGER 的有符号 64 位整数,并借 DataView.getBigInt64 校验字节序。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

float64 collapsed : true
exact increment   : 9007199254740993n changed? true
signed negative   : -4200000000000000000n
byteLength        : 24 slot bytes: 8
little-endian [1] : 9007199254740995n
big-endian [1]    : 216172782113792000n
signed 64-bit wrap: -9223372036854775808n

实现说明

演示用的数据放在这几个模块级绑定中:unsafeBase、counters、view、maxPlusOne。

使用要点

  • 原生运行时构成仅有条件——零外部包,零安装流程。
  • 跑完文件,输出里会留下标记——float64 collapsed :、exact increment :、signed negative :。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件的状态由几个模块级绑定持有:unsafeBase、counters、view。

核心语句

const maxPlusOne = new BigInt64Array([0x7fff_ffff_ffff_ffffn + 1n]);
counters[0] += 1n;

代码示例

// Number loses precision above MAX_SAFE_INTEGER (2^53 - 1 = 9007199254740991)
const unsafeBase = 9007199254740992;
console.log('float64 collapsed :', unsafeBase === unsafeBase + 1);

// BigInt64Array stores exact signed 64-bit integers (-2^63 .. 2^63 - 1)
const counters = new BigInt64Array([
  9007199254740992n,
  9007199254740995n,
  -4200000000000000000n,
]);
counters[0] += 1n;

console.log('exact increment   :', counters[0], 'changed?', counters[0] !== 9007199254740992n);
console.log('signed negative   :', counters[2]);

// Inspect the shared ArrayBuffer using DataView with explicit endianness
const view = new DataView(counters.buffer, counters.byteOffset, counters.byteLength);
console.log('byteLength        :', counters.byteLength, 'slot bytes:', BigInt64Array.BYTES_PER_ELEMENT);
console.log('little-endian [1] :', view.getBigInt64(8, true));
console.log('big-endian [1]    :', view.getBigInt64(8, false));

// Overflow wraps modulo 2^64 in two's complement
const maxPlusOne = new BigInt64Array([0x7fff_ffff_ffff_ffffn + 1n]);
console.log('signed 64-bit wrap:', maxPlusOne[0]);