Moshe Simantov
Moshe Simantov

Reputation: 4503

How to read Double from UInt64 on node.js Buffer?

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

I convert Double to UInt64BE as following:

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

Upvotes: 2

Views: 1709

Answers (1)

Moshe Simantov
Moshe Simantov

Reputation: 4503

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

Upvotes: 2

Related Questions