Skip to content

Instantly share code, notes, and snippets.

@pascaldekloe
Created April 22, 2017 11:02
Show Gist options
  • Save pascaldekloe/923499662a3aca6f5fb30e9a226b6aa4 to your computer and use it in GitHub Desktop.
Save pascaldekloe/923499662a3aca6f5fb30e9a226b6aa4 to your computer and use it in GitHub Desktop.
Big-endian 64-bit integer decoding with TypedArray
// Unmarshals an Uint8Array as a signed 64-bit integer, big-endian.
function decodeInt64(data, i, allowImprecise) {
var v = 0, j = i + 7, m = 1;
if (data[i] & 128) {
// two's complement
for (var carry = 1; j >= i; --j, m *= 256) {
var b = (data[j] ^ 255) + carry;
carry = b >> 8;
v += (b & 255) * m;
}
v = -v;
if (! allowImprecise && v < Number.MIN_SAFE_INTEGER)
throw '64-bit integer exceeds MIN_SAFE_INTEGER';
} else {
for (; j >= i; --j, m *= 256)
v += data[j] * m;
if (! allowImprecise && v > Number.MAX_SAFE_INTEGER)
throw '64-bit integer exceeds MAX_SAFE_INTEGER';
}
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment