如何在node.js Buffer上从UInt64读取Double?

时间:2015-04-08 00:00:14

标签: node.js date buffer 32bit-64bit

我想阅读 UInt64BE 并将其转换为 Double 。 我怎么能这样做?

我将 Double 转换为 UInt64BE ,如下所示:

var time = Date.now();
buffer.writeUInt32BE(parseInt(time / 0xffffffff, 10), 0);
buffer.writeUInt32BE(parseInt(time & 0xffffffff, 10), 4);

1 个答案:

答案 0 :(得分:2)

我找到了以下解决方案:

var buffer = new Buffer(8),
    time = Date.now(),

// convert number to hex
var hex = time.toString(16);
while(hex.length < 16)
    hex = '0' + hex;

// write number as UInt64
buffer.write(hex, 0, 8, 'hex');

// read UInt64 as hex and convert to Double
var num = parseInt(buffer.toString('hex', 0, 8), 16);

console.log(num === time);