What is the best way to generate a 32 bit random unsigned number in Node? Here is what I tried:
var max32 = Math.pow(2, 32) - 1
var session = Math.floor(Math.random() * max32);
I need this for a unique id.
You could use crypto.randomBytes()
like:
var crypto = require('crypto');
function randU32Sync() {
return crypto.randomBytes(4).readUInt32BE(0, true);
}
// or
function randU32(cb) {
return crypto.randomBytes(4, function(err, buf) {
if (err) return cb(err);
cb(null, buf.readUInt32BE(0, true));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With