在节点中生成随机的32位数字

fvr*_*ghl 4 javascript node.js

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

var max32 = Math.pow(2, 32) - 1
var session = Math.floor(Math.random() * max32);
Run Code Online (Sandbox Code Playgroud)

我需要一个唯一的ID。

msc*_*dex 6

您可以这样使用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));
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @Shamoon 最大的无符号 32 位整数值为 4294967295。最大的正 _signed_ 32 位整数值为 2147483647。我发布的解决方案生成任何无符号 32 位整数值,这是最初要求的。 (2认同)