Good morning,
I have to create a random number from a given 256HASH using a secret key. Everyting is fine, until I have to “convert” the hash into an integer between 0 and 15.000.000 (which is the random number). I have been playing with ord() and bytes but I don’t get anything that suits me.
My original idea was to cast the SHA256 string into an integer, and then apply a divisor to obtain the modulus. But I need a random number between a very big range. 0 to 15.000.000 (fifteen million). How would you do it?
Thanks!
A hash i basically a number, just with a base of 16. Having said that, you just have to convert it to an int.
The problem is, when you convert a hash into a int like so:
You will always get 2147483647 for 32-bit systems, which is the maximum value for intval.
My suggestion would be to cut the value of the hash to a few first characters like so
This is now the seed for the random number, you can get the random by:
Note that in some cases, you can have collisions, because you are using only the first 6 chars of the hash, but for most uses this will not be a problem. It’s up to you to decide if this is acceptable since I do not know your specific use case.
UPDATE: An alternative is to make modulo from the resulting seed – like so: