Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  85] [ 7]  / answers: 1 / hits: 8426  / 10 Years ago, wed, january 21, 2015, 12:00:00

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.


More From » node.js

 Answers
2

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));
}
}

[#39845] Tuesday, January 20, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jocelynkarsynr

Total Points: 472
Total Questions: 98
Total Answers: 96

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
jocelynkarsynr questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Sat, Jul 11, 20, 00:00, 4 Years ago
Sun, May 10, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
;