[英]Java convert byte[] to BigInteger
在Java中,我可以从String
获取BigInteger
,如下所示:
public static void main(String[] args) {
String input = "banana";
byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
BigInteger bigInteger = new BigInteger(bytes);
System.out.println("bytes: " + Arrays.toString(bytes));
System.out.println("bigInteger: " + bigInteger);
}
哪个会打印
bytes: [98, 97, 110, 97, 110, 97]
bigInteger: 108170603228769
我正在尝试使用大整数库在JavaScript中获得相同的结果。 但正如您所看到的,此代码返回不同的值:
var bigInt = require('big-integer');
function s(x) {
return x.charCodeAt(0);
}
var bytes = "banana".split('').map(s);
var bigInteger = bigInt.fromArray(bytes);
console.log("bytes: " + bytes);
console.log("bigInteger: " + bigInteger);
输出:
bytes: 98,97,110,97,110,97
bigInteger: 10890897
有没有办法通过JavaScript获得我在Java中获得的结果? 如果数组的长度为32,那还可以吗?
BigInteger(byte[])
采用二进制补码二进制表示,而bigInt.fromArray()
采用默认基数为10的数字数组。
正如dave_thompson_085所说,你可以使用base 256:
var bigInteger = bigInt.fromArray(bytes, 256);
console.log("bigInteger: " + bigInteger); // 108170603228769
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.