Created
April 22, 2017 11:02
-
-
Save pascaldekloe/923499662a3aca6f5fb30e9a226b6aa4 to your computer and use it in GitHub Desktop.
Big-endian 64-bit integer decoding with TypedArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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