Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert byte[] to BigInteger

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?

like image 944
sietzevliegen Avatar asked Nov 08 '22 01:11

sietzevliegen


1 Answers

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
like image 82
Karol Dowbecki Avatar answered Nov 14 '22 22:11

Karol Dowbecki