Skip to content

Instantly share code, notes, and snippets.

@Fantasim
Last active February 7, 2021 22:37
Show Gist options
  • Save Fantasim/c92060cbf8494be52f23887caf7f81fe to your computer and use it in GitHub Desktop.
Save Fantasim/c92060cbf8494be52f23887caf7f81fe to your computer and use it in GitHub Desktop.
Bytes array to BigInt in Typescript
const MAX_UINT_8 = BigInt(256)
const MAX_UINT_16 = BigInt(65536)
const MAX_UINT_32 = BigInt(4294967296)
const MAX_UINT_64 = BigInt(18446744073709551616)
export const ByteArrayToInt = (value: Uint8Array, isNegative: boolean): BigInt => {
let n = BigInt(0);
let MAX = MAX_UINT_8
switch(value.length){
case 1:
MAX = MAX_UINT_8
break;
case 2:
MAX = MAX_UINT_16
break;
case 4:
MAX = MAX_UINT_32
break;
case 8:
MAX = MAX_UINT_64
break;
}
const readBigUInt64LE = (buffer: Buffer, offset = 0) => {
const first = buffer[offset];
const last = buffer[offset + 7];
if (first === undefined || last === undefined) {
throw new Error('Out of bounds');
}
const lo = first +
buffer[++offset] * 2 ** 8 +
buffer[++offset] * 2 ** 16 +
buffer[++offset] * 2 ** 24;
const hi = buffer[++offset] +
buffer[++offset] * 2 ** 8 +
buffer[++offset] * 2 ** 16 +
last * 2 ** 24;
return BigInt(lo) + (BigInt(hi) << BigInt(32));
}
if (value.length == 8) {
n = readBigUInt64LE(Buffer.from(value), 0)
} else {
switch (value.length){
case 4:
n = BigInt(Buffer.from(value).readUInt32LE(0))
break;
case 2:
n = BigInt(Buffer.from(value).readUInt16LE(0))
break;
case 1:
n = BigInt(value[0])
break;
}
}
if (isNegative) {
n -= MAX
}
return n
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment