我想在 NodeJS 中使用 randomBytes 生成随机数。环顾四周后,我发现了一种将缓冲区转换为整数的方法;
const integer = parseInt(buffer.toString("hex"), 16)
Run Code Online (Sandbox Code Playgroud)
使用这个方法有什么问题吗?我见过使用buffer.readUIntBE其他类似方法的解决方案。我想知道他们比上面的解决方案有什么优势
ste*_*ino 10
也许不一定是错误的,但至少可以说,将缓冲区转换为其十六进制字符串表示形式,然后将其解析为数字似乎不是很简单并且不必要地消耗资源。
缓冲区read方法主要执行数字运算(例如此处),并且消耗的资源应该少得多,同时在我看来,对于阅读代码的人来说也更容易解释。
function randomUInt32() {
return crypto.randomBytes(4).readUInt32BE();
}
Run Code Online (Sandbox Code Playgroud)
与
function randomUInt32() {
return parseInt(crypto.randomBytes(4).toString("hex"), 16);
}
Run Code Online (Sandbox Code Playgroud)