将sha256字符串转换为数字 – Java

huangapple go评论52阅读模式
英文:

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&#39;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.

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-js --&gt;

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

&lt;!-- end snippet --&gt;



</details>



huangapple
  • 本文由 发表于 2023年2月14日 07:47:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定