6

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

2 Answers 2

12
+50

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.