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

Converting random bytes to an integer range - how?

本文关键字:整数 范围 转换 字节 随机      更新时间:2023-09-26

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

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

有什么想法吗?

您可以使用下面的代码从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(new Uint32Array(1))[0] / 0x100000000;
console.log(random);

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

现在它在节点本身中实现https://nodejs.org/api/crypto.html#crypto_crypto_randomint_min_max_callback