Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NodeJS buffer to integer

Tags:

node.js

buffer

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

like image 931
Ernest Okot Avatar asked Sep 04 '26 02:09

Ernest Okot


1 Answers

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);
}
like image 181
stefanobaghino Avatar answered Sep 06 '26 20:09

stefanobaghino