1

How to generate (in JavaScript or Node.JS) float in range from 0.00000000 - 100.00000000 from given long HEX hash? For example SHA-256?

I am open to solutions with crypto library because I using it to generate given hash :)

Baterka
  • 622
  • 4
  • 9
  • 20
  • quite complicated, but possible https://stackoverflow.com/questions/46447807/javascript-parse-string-to-long/46583936#46583936 – Jonas Wilms Apr 10 '18 at 18:02

1 Answers1

3

If you're not concerned about precision loss, and your hex strings are of a fixed length (as with SHA-256), you could simply map from one value space to the other:

function hexStrToFraction(hexStr) {
    // Expresses a hexadecimal string of N characters as a fraction
    // of one above its maximum possible value (16^N).
    // Returns a number between 0 and 1.
    return parseInt(hexStr, 16) / Math.pow(16, hexStr.length);
}

function sha256ToPercent(sha256) {
    return 100 * hexStrToFraction(sha256);
}

Note that the precision loss is high enough to render the majority of a SHA-256 redundant:

var a = 'b2339969703a8c4b49e4a5c99cca6013ed455f52d06f8f03adb927aee7d9c3c0'
var b = 'b2339969703a8c8b8504772b860b9ed2cb6aa0186ff6750981e7ccd5344e4bf1'
//                     ^ differences start here
hexStrToFraction(a) === hexStrToFraction(b) // evaluates true
Joss
  • 401
  • 4
  • 7
  • I don't care about precision loss that much. Thanks. This working – Baterka Apr 10 '18 at 18:59
  • Could you explain your code please? Maybe some documentation that `hexStrToDecimal` returns a value between 0 and 1 and how division by 16 to the power of `maxLength` helps with that. – Maarten Bodewes Apr 10 '18 at 21:23
  • I guess maxLength is not really needed. The hexadecimal string will always be 64 characters in size, so you may as well use the size of hexStr itself (presuming it contains *just* hexadecimal characters). – Maarten Bodewes Apr 10 '18 at 21:31
  • 1
    Thanks @MaartenBodewes - now edited as suggested. My original thinking with specifying `maxLength` was to be visually explicit about the constant length requirement, but on reflection the degree of precision loss makes the explicitness somewhat pointless. – Joss Apr 11 '18 at 18:26
  • Is there way to not loss so much? – Baterka Apr 14 '18 at 09:38
  • You could try a library for increasing precision such as [bignumber](https://github.com/MikeMcl/bignumber.js/). Though you'd be tied into using it for any subsequent arithmetic that requires high precision. What are you planning to use this value for? It might be that there's a more convenient value format for your purposes than using a single number. – Joss Apr 17 '18 at 16:19