Node: Generate 6 digits random number using crypto.randomBytes

前端 未结 6 1443
陌清茗
陌清茗 2020-12-16 20:44

What is the correct way to generate exact value from 0 to 999999 randomly since 1000000 is not a power of 2?

This is my approa

6条回答
  •  孤街浪徒
    2020-12-16 21:10

    Here's a simple piece of code that uses the randomBytes() function.

    require('crypto').randomBytes(2, (err: Error, buf: Buffer) => 
        console.log(Number.parseInt(buf.toString('hex'), 16)));
    

提交回复
热议问题