[英]Java convert byte[] to BigInteger
In Java, I can get a BigInteger
from a String
like this: 在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);
}
Which will print 哪个会打印
bytes: [98, 97, 110, 97, 110, 97]
bigInteger: 108170603228769
I'm trying to get the same result in JavaScript using the big-integer library . 我正在尝试使用大整数库在JavaScript中获得相同的结果。 But as you can see this code returns a different value:
但正如您所看到的,此代码返回不同的值:
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);
output: 输出:
bytes: 98,97,110,97,110,97
bigInteger: 10890897
Is there a way to get the result I'm getting in Java with JavaScript? 有没有办法通过JavaScript获得我在Java中获得的结果? And would that be possible also if the array has a length of 32?
如果数组的长度为32,那还可以吗?
BigInteger(byte[])
takes the two's-complement binary representation while bigInt.fromArray()
takes an array of digits with a default base of 10. BigInteger(byte[])
采用二进制补码二进制表示,而bigInt.fromArray()
采用默认基数为10的数字数组。
As dave_thompson_085 said, you can use base 256: 正如dave_thompson_085所说,你可以使用base 256:
var bigInteger = bigInt.fromArray(bytes, 256);
console.log("bigInteger: " + bigInteger); // 108170603228769
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.