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

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

Convert sha256 string to number - Java

问题

Java

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

Result:
4

  1. <details>
  2. <summary>英文:</summary>
  3. 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.
  4. What&#39;s the best way to get the same result shown in JS using Java?
  5. **JS**

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

  1. **Result:**
  2. 2
  3. **Java**

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

  1. **Result:**
  2. 4
  3. </details>
  4. # 答案1
  5. **得分**: 3
  6. 正确的值是 `4`JavaScript 片段的结果是不正确的,因为数字太大无法准确表示。请使用 `BigInt` 替代。
  7. <details>
  8. <summary>英文:</summary>
  9. 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.
  10. &lt;!-- begin snippet: js hide: false console: true babel: false --&gt;
  11. &lt;!-- language: lang-js --&gt;
  12. const hash = &quot;806abe48226985c5fb0e878792232204d74643e190e25a4c20a97748d52b191c&quot;
  13. console.log(Number.isSafeInteger(parseInt(hash, 16))); // do not use this!
  14. console.log((BigInt(&#39;0x&#39; + hash) % 11n).toString());
  15. &lt;!-- end snippet --&gt;
  16. </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:

确定