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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With