Reputation: 988
I want to generate random numbers using randomBytes in NodeJS. After looking around I found a method that converts buffers to integers;
const integer = parseInt(buffer.toString("hex"), 16)
Is there something wrong with using this method. I've seen other solutions that use buffer.readUIntBE
and other similar methods. I'm wondering what advantage they have over the solution above
Upvotes: 6
Views: 16443
Reputation: 49
Hope you like the following solution for number to byte conversion and byte to number:
const {Int64BE} = require("int64-buffer");
let time = (new Date()).getTime();
console.log("Original Number : " + time);
// Number to buffer conversion ///////////
let timeBuffer = new Int64BE(time);
let buf = timeBuffer.toBuffer();
console.log("Buffer Format : " + JSON.stringify(buf));
//From buffer to number - approach 1 ///////////////
let num = new Int64BE(buf)
num = num.toNumber();
console.log("Back to Nnumber using aproach 1: " + num);
//from buffer to number - approach 2 ///////////////
let timestamp = Buffer.from( buf.slice(0, 4)).readUInt32BE();
timestamp = 4294967296 * timestamp + Buffer.from( buf.slice(4, 8) ).readUInt32BE();
console.log("Back to Nnumber using aproach 2: " + timestamp);
Upvotes: 0
Reputation: 12804
Maybe not necessarily wrong, but converting a buffer to its hexadecimal string representation to then parse it into a number seems, to say the least, not very straightforward and unnecessarily resource-consuming.
The buffer read
methods mostly perform numeric operations (e.g. here) and should be much less resource-consuming while also, in my opinion, being easier to interpret for whoever reads your code.
function randomUInt32() {
return crypto.randomBytes(4).readUInt32BE();
}
vs.
function randomUInt32() {
return parseInt(crypto.randomBytes(4).toString("hex"), 16);
}
Upvotes: 12