问题描述
我正在使用 jsbn 库来管理 JavaScript 应用程序中的 BigInteger。 似乎 negate 功能不太好。
我希望 negate 函数像 Java 那样工作。
BigInteger minusOne = BigInteger.ONE.negate(); // -1
但是使用 jsbn 库,以下代码会产生此结果...
var BigInteger = require('jsbn').BigInteger;
var bi = BigInteger.ONE;
console.log(bi); // 1
console.log(bi.negate()); // 268435455 but should be -1,no ??
您可以在此处尝试此代码https://runkit.com/gikoo/jsbn-negate-function/1.0.0
解决方法
BigInteger 以某种方式存储数字,允许它们跟踪比 JavaScript 可以跟踪的更大的数字。他们是如何做到的,你应该考虑一个黑匣子——当你准备回到一个正常的 int 时,你需要做 bi.negate().intValue()
,或者如果它真的太大了,bi.negate().toString()