Search code examples
javascriptnode.jsintegerbufferbyte

JavaScript: Read 8 bytes to 64 bit integer


I have a buffer object which contains eight bytes. These eight bytes should now be interpreted as 64 bit integer.

Currently I use following algorithm:

var int = buff[0];

for (var i = 1; i < buff.length; i++) {
    int += (buff[i] * Math.pow(2, 8 * i));
}

console.log(int);

this works but I believe there are better ways (maybe using Uint64Array).

Unfortunately I cannot find how a Uint16Array could help me here for.

Regards

Update:

// puts two 32bit integers to one 64bit integer
var bufInt = (buf.readUInt32BE(0) << 8) + buf.readUInt32BE(4);

Solution

  • Javascript does not support 64 bit integers, because the native number type is a 64-bit double, giving only 53 bits of integer range.

    You can create arrays of 32-bit numbers (i.e. Uint32Array) but if there were a 64-bit version of those there'd be no way to copy values from it into standalone variables.