简体   繁体   中英

floating point number from crypto.randomBytes() in javascript

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()

Suppose you have a series of bytes randomly selected with uniform distribution over [0, 256). Take seven of those bytes, say a 0 , a 1 ,… a 6 . Calculate (((((((a 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 the residue of a 6 modulo 32. This takes five bits of a 6 . 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 2 53 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM