将随机字节转换为整数范围 - 如何? [英] Converting random bytes to an integer range - how?
问题描述
我试图通过读取crypto.randomBytes()来获取范围内的随机整数。
I'm trying to get a random integer within a range by reading from crypto.randomBytes().
现在,我的问题是我不知道如何从该字节流中读取整数。我想,生成一个范围只是抛弃不在范围内的整数。
Now, my problem is that I do not know how to read integers from that byte stream. I imagine generating a range is simply a matter of 'throwing away' the ints not in range.
任何想法?
推荐答案
您可以使用以下代码从 crypto.randomBytes
获取一个32位整数。如果您需要多个字节,可以从 crypto.randomBytes
中请求更多字节,然后使用 substr
单独选择和转换每个整数。
You can get one 32 bit integer from crypto.randomBytes
with the code below. If you need more than one you can ask for more bytes from crypto.randomBytes
and then use substr
to individually select and convert each integer.
crypto.randomBytes(4, function(ex, buf) {
var hex = buf.toString('hex');
var myInt32 = parseInt(hex, 16);
});
话虽如此,你可能只想使用 Math.floor(数学.random()* maxInteger)
Having said that, you might want to just use Math.floor(Math.random() * maxInteger)
这篇关于将随机字节转换为整数范围 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!