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.
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.
Share Improve this question asked Dec 22, 2012 at 10:55 Van CodingVan Coding 24.6k25 gold badges92 silver badges137 bronze badges 1- Sorry, don't have time to make the signed function. But you can do yourself by reading in 2 32 bit parts and then building a signed number from that. – Esailija Commented Dec 22, 2012 at 11:25
3 Answers
Reset to default 8Javascript uses only 64 bit double precision floats. To read a long number you have to read two 32 bit integers and shift the high 32 bits to the left. Also note that there possibly is an information loss for long values not in the range of 9007199254740992 <= x <= -9007199254740992 since the internal representation uses 1 bit for the sign and 11 bits for the exponent.
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);
}
In the latest Node.js (12.0.0), you can use buf.readBigInt64BE
:))