如何在Javascript中从字节数组中获得一个BigInteger


我的问题是:

我有一个base64编码的字符串,一个很长的字符串(344个字符)。
当我解码这个字符串时,我可以获得一个字节数组。

假设我的base64编码字符串是ALVuSLbT
解码后,它给了我以下数组:[0, 181, 110, 72, 182, 211]

我需要得到这个数字:779239339731(原始编码值)。
我知道怎么手动操作。
000000000000000000000000000000000000000000000000000000001011010100000000000000000000000000000000000000000000000001101110000000000000000000000000000000000000000000000000010010000000000000000000000000000000000000000000000000001011011000000000000000000000000000000000000000000000000011010011

在这个简单的例子中,我可以很容易地使用parseInt(binaryString, 2)并将数字相加。但我原来的绳子太大了。

我想要一个大的数字,可以将这个数字转换为字符串('779239339731')。
我没有找到一种方法来做到这一点,或者一个BigInteger/bignnumber javascript库,允许我传递一个字节数组来创建BigInteger对象。

您可以查看这个文件。

有人能帮我一下吗?在Javascript中有办法处理这样的事情吗?

我不明白为什么要解析-使用BigInteger库https://rawgithub.com/silentmatt/javascript-biginteger/master/biginteger.js

工作jsFiddle示例- http://jsfiddle.net/svejdo1/sdV8L/

var exponentB64 = 'ALVuSLbT';
var exponentBytes = base64_decode(exponentB64);
var result = new BigInteger(0);
var multiplier = new BigInteger(1);
for(var i = exponentBytes.length - 1; i >= 0; i--) {
    result = result.add(multiplier.multiply(exponentBytes[i]));
    multiplier = multiplier.multiply(256);
}
document.write(result.toString());

function base64_decode(base64String) {
  var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var h1, h2, h3, h4, o1, o2, o3, bits, i = 0, bytes = [];
  do {
    h1 = b64.indexOf(base64String.charAt(i++));
    h2 = b64.indexOf(base64String.charAt(i++));
    h3 = b64.indexOf(base64String.charAt(i++));
    h4 = b64.indexOf(base64String.charAt(i++));
    bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
    o1 = bits >> 16 & 0xff;
    o2 = bits >> 8 & 0xff;
    o3 = bits & 0xff;
    bytes.push(o1);
    bytes.push(o2);
    bytes.push(o3);
  } while (i < base64String.length);
  return bytes;
}

最新更新