首页 > 解决方案 > BigInt 对大数行为不端

问题描述

我有两个 BigInt 完全行为不端的情况。

为了完整起见,我附上了BigInt BigInt doc的文档并引用

BigInt.asIntN() 将 BigInt 值包装为 -2^(width-1) 和 2^(width-1 - 1) 之间的有符号整数。

BigInt.asUintN() 将 BigInt 值包装为 0 到 2^(width - 1) 之间的无符号整数。

对于 64 位正整数,最大值为9223372036854775808 对于 64 位有符号整数,最小值为-9223372036854775808

情况1:

const max: BigInt = BigInt.asUintN(64, BigInt(9223372036854775806));
console.log("max is: " + max);

并打印

9223372036854775808 when it should print:
9223372036854775806

为什么?它适用于 10、100 等小数字,但在限制上失败。

案例二:

const min: BigInt = BigInt.asIntN(64, BigInt(-9223372036854775808));
console.log("bits: " + min.toString(2).length);

并打印:

bits: 65

当清楚地根据文档时,它应该是64

标签: javascript

解决方案


您可以将数字作为字符串转换为BigInt.

const max = BigInt.asUintN(64, BigInt('9223372036854775806'));
console.log("max is: " + max);


推荐阅读