Floating point from crypto.randomBytes () in javascript

How to convert an array of bytes returned from crypto.randomBytes to a floating point number a? I am writing a small replacement for Math.random ()

+2
source share
1 answer

Suppose you have a series of bytes randomly selected with a uniform distribution over [0, 256). Take seven of these bytes, for example 0 , a 1 , ... a 6 . Calculate ((((((((< 6 % 32) / 32 + a 5 ) / 256 + a 4 ) / 256 + a 3 ) / 256 + a 2 ) / 256 + a 1 ) / 256 + a 0 ) / 256.

Explanation: a 6 % 32 denotes a remainder of 6 modulo 32. This takes up five bits of 6 . Then dividing by 32 β€œshifts” these bits to the right of the notation, eight new bits are added, dividing by 256 β€œshifts” the right eight bits, and so on, until we have 53 bits.

This gives 2 53 possible results in [0, 1). More can be done because the resolution of the floating point is smaller, because the values ​​are close to zero, but then there are problems with uniformity and other problems.

+3
source

All Articles