Java convert byte[] to BigInteger

sietzevliegen :

In Java, I can get a BigInteger from a String like this:

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. 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? And would that be possible also if the array has a length of 32?

Karol Dowbecki :

BigInteger(byte[]) takes the two's-complement binary representation while bigInt.fromArray() takes an array of digits with a default base of 10.

As dave_thompson_085 said, you can use base 256:

var bigInteger = bigInt.fromArray(bytes, 256);
console.log("bigInteger: " + bigInteger); // 108170603228769

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71124&siteId=1