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

时间:2022-02-11 16:05:22

I want to read an UInt64BE and convert it to Double. How can I do that?

我想读一个UInt64BE并将其转换为Double。我怎样才能做到这一点?

I convert Double to UInt64BE as following:

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

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

1 个解决方案

#1


1  

I found the following solution:

我找到了以下解决方案:

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

#1


1  

I found the following solution:

我找到了以下解决方案:

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