Converting random bytes to an integer range – how?

Converting random bytes to an integer range – how?

Problem

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.

Any ideas?

Problem courtesy of: Stephan Tual

Solution

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);
});

Having said that, you might want to just use Math.floor(Math.random() * maxInteger)

Solution courtesy of: Daniel

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *