gpt4 book ai didi

javascript - 在 Node 中生成随机 32 位数字

转载 作者:搜寻专家 更新时间:2023-10-31 23:38:26 25 4
gpt4 key购买 nike

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

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

我需要这个作为唯一 ID。

最佳答案

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

关于javascript - 在 Node 中生成随机 32 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28061016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com