在Node中生成随机的32位数字

6

在Node中生成一个32位的无符号随机数,最好的方法是什么?这是我尝试过的:

var max32 = Math.pow(2, 32) - 1
var session = Math.floor(Math.random() * max32);

我需要这个来生成唯一标识符。

1
最大的16位数是65535,所以如果你得到了100,000,那么你肯定有一些严重的问题。 - Pointy
@Pointy 抄写错了。 - fvrghl
1
我经常使用 Math.random()*2**32|0 来表示 int32,并使用 Math.random()*2**32>>>0 来表示 uint32 - bryc
1个回答

12

你可以使用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));
  }
}

1
有时会生成比 2147483651 更大的数字,这是我所知道的最大无符号32位整数。 - Shamoon
2
@Shamoon 最大的无符号32位整数值为4294967295。最大的正有符号32位整数值为2147483647。我发布的解决方案生成任何无符号32位整数值,这也是最初要求的。 - mscdex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接