4

How do I convert the array of bytes returned from crypto.randomBytes into a to a floating point number? I'm writing a small replacement for Math.random()

1 Answer 1

5

Suppose you have a series of bytes randomly selected with uniform distribution over [0, 256). Take seven of those bytes, say a0, a1,… a6. Calculate (((((((a6 % 32)/32 + a5)/256 + a4)/256 + a3)/256 + a2)/256 + a1)/256 + a0)/256.

Explanation: a6 % 32 denotes the residue of a6 modulo 32. This takes five bits of a6. Then division by 32 “shifts” these bits to the right of the radix point, eight new bits are added, a division by 256 “shifts” right eight bits, and so on until we have 53 bits.

This provides 253 possible results in [0, 1). It is possible to provide more since the floating-point resolution is finer as values get closer to zero, but then there are problems with uniformity and other issues.

Sign up to request clarification or add additional context in comments.

3 Comments

I really appreciate your answer, and this is a humble implementation of what you proposed.
I have a question though, why you specified 53 bits and not 52 bits that are the total bits for float mantissa?
@Argento: The floating-point format used in Javascript, IEEE-754 binary64, has 53 bits in the mathematical significand (the preferred term; “mantissa” is an old term for the fraction portion of a logarithm). In bytes representing a floating-point number it is encoded with 52 bits in the primary significand field and one leading bit via the exponent field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.