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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With