The code below in JS converts a Hash to a number, but I tried to write a similar code in Java and both return different results.
What's the best way to get the same result shown in JS using Java?
JS
const hash = "806abe48226985c5fb0e878792232204d74643e190e25a4c20a97748d52b191c"
console.log(parseInt(hash, 16) % 11);
Result:
2
Java
String hash = "806abe48226985c5fb0e878792232204d74643e190e25a4c20a97748d52b191c";
BigInteger bigInt = new BigInteger(hash, 16);
System.out.println(bigInt.mod(BigInteger.valueOf(11)).intValue());
Result:
4
The correct value is 4
. The result from the JavaScript snippet is incorrect, as the number is too large to be represented accurately. Use BigInt
instead.
const hash = "806abe48226985c5fb0e878792232204d74643e190e25a4c20a97748d52b191c"
console.log(Number.isSafeInteger(parseInt(hash, 16))); // do not use this!
console.log((BigInt('0x' + hash) % 11n).toString());