sie*_*gen 5 javascript java arrays biginteger uint8array
在Java中,我可以BigInteger从String这样的:
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);
}
Run Code Online (Sandbox Code Playgroud)
哪个会打印
bytes: [98, 97, 110, 97, 110, 97]
bigInteger: 108170603228769
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用大整数库在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);
Run Code Online (Sandbox Code Playgroud)
输出:
bytes: 98,97,110,97,110,97
bigInteger: 10890897
Run Code Online (Sandbox Code Playgroud)
有没有办法通过JavaScript获得我在Java中获得的结果?如果数组的长度为32,那还可以吗?
BigInteger(byte[])采用补码二进制表示形式,而bigInt.fromArray()采用默认基数为 10 的数字数组。
正如 dave_thompson_085 所说,您可以使用基数 256:
var bigInteger = bigInt.fromArray(bytes, 256);
console.log("bigInteger: " + bigInteger); // 108170603228769
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
346 次 |
| 最近记录: |