What would be the best way to read an Int64BE from a node.js buffer into a Number primitive, like readInt32BE reads an Int32?
I know that I'll lose precision with numbers +/- 9'007'199'254'740'992, but i won't get such high numbers in the protocol I want to implement.
Javascript uses 32 bit integers and 32 bit floats. So you have to read two 32 bit integers and shift one to the left while converting it to a float. In this code this is achieved by a multiplication with a float.
Since the low part can be negative but must be treated as unsigned, a correction is added.
function readInt64BEasFloat(buffer, offset) {
var low = readInt32BE(buffer, offset + 4);
var n = readInt32BE(buffer, offset) * 4294967296.0 + low;
if (low < 0) n += 4294967296;
return n;
}
Don't try and code the conversion yourself, use a tested version like node-int64.
var Int64 = require('node-int64');
function readInt64BEasFloat(buffer, offset) {
var int64 = new Int64(buffer, offset);
return int64.toNumber(true);
}
As of Node v0.12.7 you can use buf.readIntBE(offset, 8).
Here's the docs => https://nodejs.org/docs/v0.12.7/api/buffer.html#buffer_buf_readuintle_offset_bytelength_noassert
Here's the commit where the feature was added => https://github.com/joyent/node/commit/83d7d9e6d81fc35764a9000b6d7b17a0e7d8cc92
Hope that helps