JavaScript typed arrays: 64-bit integers?

JavaScript typed arrays, implemented in Firefox 4 and Chrome 7, are a very efficient way of storing and working with binary data in JavaScript. However, the current implementations only provide integer views up to 32 bits per member, with Int32Array and Uint32Array. Are 64-bit integer views being planned for implementation? How can I implement 64-bit integer views? How much slower will they be?

Answers:

Answer

There's no practical way to implement an Int64Array, because all numbers in JavaScript are 64-bit floating point numbers, which only have 53 bits of precision. Like Simeon said in his comment, you could use a big integer library, but it would be much slower.

If you really need an array of 64-bit integers, regardless of performance, the Google Closure library has a 64-bit Long class that I would imagine is faster than a more general big integer library. I've never used it though, and I don't know if you can separate it easily from the rest of the library.

Answer

You can use Float64Array or Float32Array. But I don't know if that's what you're looking for, because it's a float.

Answer

As said you cannot safely go beyond the 2^52-1 integer with Javascript numbers, because in Javascript numbers are really always represented as double precision 64 bit floating point which only has 53 significant bits with the rest being for the exponent, so you'll loose precise integer precision after that.

But here's at least how you can check for whether an unsigned 64 bit long integer in a Unit8Array is less than 2^52-1 and then safely read it if you want:

const dataView = new DataView(unit8Array.buffer);
const hi = dataView.getUint32(0);
if (hi > 0x1fffff) {
  throw new Error(
    'Cannot safely parse uints over 2^53 - 1 (0x1fffffffffffff) in to a 64 bit float.' +
    ' PropertyKey: ' + propertyKey,
  );
}
const lo = dataView.getUint32(4);
const numberValue = (hi * 0xffffffff) + lo;

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.