在Node中生成一个32位的无符号随机数,最好的方法是什么?这是我尝试过的:
var max32 = Math.pow(2, 32) - 1
var session = Math.floor(Math.random() * max32);
我需要这个来生成唯一标识符。
在Node中生成一个32位的无符号随机数,最好的方法是什么?这是我尝试过的:
var max32 = Math.pow(2, 32) - 1
var session = Math.floor(Math.random() * max32);
你可以使用crypto.randomBytes()
,例如:
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));
}
}
2147483651
更大的数字,这是我所知道的最大无符号32位整数。 - Shamoon
Math.random()*2**32|0
来表示int32
,并使用Math.random()*2**32>>>0
来表示uint32
。 - bryc