javascript - 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
解决方案
您可以将数字作为字符串转换为BigInt
.
const max = BigInt.asUintN(64, BigInt('9223372036854775806'));
console.log("max is: " + max);
推荐阅读
- javascript - react.js 'x' 被分配了一个值,但从未使用过 no-unused-vars
- javascript - 无法将异步函数移动到 Appium PageObjects
- c - [*num - '0'] 是什么意思?
- php - Postgres createdb 从 php exec 运行
- java - 通过 WebDriverManager 使用 Selenium 时如何修复 java.net.UnknownHostException: npm.taobao.org
- clickhouse - 我可以在 quantilesExact 中使用 0 和 1 值吗
- node.js - 使用 NodeJS 验证输入以接受所有语言的字母数字
- ios - SwiftUI 中的数据关联
- vue.js - vue.js 中的复选框选择问题
- python - 使用 python 和 babel 获取翻译的国籍名称列表(或者其他什么?)