英文:
Convert sha256 string to number - Java
问题
Java
String hash = "806abe48226985c5fb0e878792232204d74643e190e25a4c20a97748d52b191c";
BigInteger bigInt = new BigInteger(hash, 16);
System.out.println(bigInt.mod(BigInteger.valueOf(11)).intValue());
Result:
4
<details>
<summary>英文:</summary>
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
</details>
# 答案1
**得分**: 3
正确的值是 `4`。JavaScript 片段的结果是不正确的,因为数字太大无法准确表示。请使用 `BigInt` 替代。
<details>
<summary>英文:</summary>
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.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const hash = "806abe48226985c5fb0e878792232204d74643e190e25a4c20a97748d52b191c"
console.log(Number.isSafeInteger(parseInt(hash, 16))); // do not use this!
console.log((BigInt('0x' + hash) % 11n).toString());
<!-- end snippet -->
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论