将 SHA-256 字符串转换为数字 - Java

问题描述 投票:0回答:1

下面的 JS 代码将 Hash 转换为数字,但我尝试用 Java 编写类似的代码,但都返回不同的结果。

使用 Java 在 JS 中获得相同结果的最佳方法是什么?

JS

const hash = "806abe48226985c5fb0e878792232204d74643e190e25a4c20a97748d52b191c"
console.log(parseInt(hash, 16) % 11);

结果:
2

Java

String hash = "806abe48226985c5fb0e878792232204d74643e190e25a4c20a97748d52b191c";
BigInteger bigInt = new BigInteger(hash, 16);
System.out.println(bigInt.mod(BigInteger.valueOf(11)).intValue());

结果:
4

javascript java sha256
1个回答
3
投票

正确的值为

4
。 JavaScript 代码片段的结果不正确,因为数字太大而无法准确表示。请使用
BigInt
来代替。

const hash = "806abe48226985c5fb0e878792232204d74643e190e25a4c20a97748d52b191c"
console.log(Number.isSafeInteger(parseInt(hash, 16))); // do not use this!
console.log((BigInt('0x' + hash) % 11n).toString());

© www.soinside.com 2019 - 2024. All rights reserved.