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

Javascript 如何将随机字节转换为整数范围?,javascript,node.js,Javascript,Node.js,我试图通过读取crypto.randomBytes()得到一个范围内的随机整数 现在,我的问题是我不知道如何从字节流中读取整数。我想象生成一个范围只是“扔掉”不在范围内的整数 有什么想法吗?您可以使用下面的代码从crypto.randomBytes中获得一个32位整数。如果需要多个字节,可以从crypto.randomBytes请求更多字节,然后使用substr分别选择和转换每个整数 crypto.randomBytes(4, function(ex, buf) { var hex = bu

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

现在,我的问题是我不知道如何从字节流中读取整数。我想象生成一个范围只是“扔掉”不在范围内的整数


有什么想法吗?

您可以使用下面的代码从
crypto.randomBytes
中获得一个32位整数。如果需要多个字节,可以从
crypto.randomBytes
请求更多字节,然后使用
substr
分别选择和转换每个整数

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

话虽如此,您可能只想使用
Math.floor(Math.random()*maxInteger)
来获得NodeJS中
[0,1)
间隔内的加密安全且均匀分布的值(即与
Math.random()
相同)

const random = crypto.randomBytes(4).readUInt32LE() / 0x100000000;
console.log(random); //e.g. 0.9002735135145485
或者在浏览器中

const random=window.crypto.getRandomValues(新的UINT32数组(1))[0]/0x100000000;
console.log(随机);
现在它是在节点本身中实现的

这个问题可能会有帮助:如果你能做到这一点,你可以通过Math.floor(randomFloat()*maxInteger)得到一个介于0和(maxInteger-1)之间的整数。这正是我需要的,谢谢!这是一个单行版本:parseInt(crypto.randomBytes(4).toString('hex'),16);使用crypto.randomBytes()的一个很好的理由而不仅仅是数学。随机就是因为这个
const { randomInt } = await import('crypto');

const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);