将随机字节转换为整数范围 - 如何?

Ste*_*ual 7 javascript node.js

我试图通过从crypto.randomBytes()读取一个范围内的随机整数.

现在,我的问题是我不知道如何从该字节流中读取整数.我想,生成一个范围只是"抛弃"不在范围内的整数.

有任何想法吗?

Dan*_*iel 15

您可以crypto.randomBytes使用以下代码获取一个32位整数.如果您需要多个字节,可以从中请求更多字节crypto.randomBytes,然后使用它substr来单独选择和转换每个整数.

crypto.randomBytes(4, function(ex, buf) {
  var hex = buf.toString('hex');
  var myInt32 = parseInt(hex, 16);
});
Run Code Online (Sandbox Code Playgroud)

话虽如此,您可能只想使用 Math.floor(Math.random() * maxInteger)


gog*_*ogo 6

在 NodeJS 中获取区间内(即与 相同)内加密安全且均匀分布的值[0,1)Math.random()

const random = crypto.randomBytes(4).readUInt32LE() / 0x100000000;
console.log(random); //e.g. 0.9002735135145485
Run Code Online (Sandbox Code Playgroud)

或在浏览器中

const random = crypto.randomBytes(4).readUInt32LE() / 0x100000000;
console.log(random); //e.g. 0.9002735135145485
Run Code Online (Sandbox Code Playgroud)