Java 将 byte[] 转换为 BigInteger
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
我正在尝试使用 big-integer library 在 Java 脚本中获得相同的结果。但是正如您所见,此代码 returns 不同的值:
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[])
takes the two's-complement binary representation while bigInt.fromArray()
采用默认基数为 10 的数字数组。
正如dave_thompson_085所说,你可以使用base 256:
var bigInteger = bigInt.fromArray(bytes, 256);
console.log("bigInteger: " + bigInteger); // 108170603228769
在 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
我正在尝试使用 big-integer library 在 Java 脚本中获得相同的结果。但是正如您所见,此代码 returns 不同的值:
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[])
takes the two's-complement binary representation while bigInt.fromArray()
采用默认基数为 10 的数字数组。
正如dave_thompson_085所说,你可以使用base 256:
var bigInteger = bigInt.fromArray(bytes, 256);
console.log("bigInteger: " + bigInteger); // 108170603228769