Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 432
bodokaiser Avatar asked Jan 07 '13 16:01

bodokaiser


People also ask

Does JavaScript support 64-bit integers?

Since JavaScript does not natively support 64-bit integers, 64-bit Ids are instead represented as strings. Strings containing 64-bit Ids are distinguished from ordinary strings through use of the Id64String type alias.

Is JavaScript 32 bit or 64-bit?

JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision.

Are JavaScript integers 32 bit?

JavaScript Uses 32 bits Bitwise Operands JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.


1 Answers

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.

like image 174
Alnitak Avatar answered Oct 09 '22 23:10

Alnitak