繁体   English   中英

将 NodeJS 缓冲区转换为整数

[英]Convert NodeJS buffer to integer

我想在 NodeJS 中使用 randomBytes 生成随机数。 环顾四周后,我发现了一种将缓冲区转换为整数的方法;

const integer = parseInt(buffer.toString("hex"), 16)

使用这种方法有什么问题吗。 我见过使用buffer.readUIntBE和其他类似方法的其他解决方案。 我想知道他们比上述解决方案有什么优势

也许不一定是错误的,但是将缓冲区转换为其十六进制字符串表示形式,然后将其解析为数字,至少可以说,这似乎不是很简单且不必要地消耗资源。

缓冲区read方法主要执行数字操作(例如here ),并且资源消耗应该少得多,而且在我看来,对于阅读您的代码的人来说更容易解释。

function randomUInt32() {
   return crypto.randomBytes(4).readUInt32BE();
}

对比

function randomUInt32() {
   return parseInt(crypto.randomBytes(4).toString("hex"), 16);
}

希望您喜欢以下数字到字节转换和字节到数字的解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM