Skip to content

Instantly share code, notes, and snippets.

@maca134
Last active November 30, 2019 03:13
Show Gist options
  • Save maca134/3cf54a36ff60220c50a11aee9fa22847 to your computer and use it in GitHub Desktop.
Save maca134/3cf54a36ff60220c50a11aee9fa22847 to your computer and use it in GitHub Desktop.
BigInt to Buffer and Buffer to BigInt Nodejs
function bigIntToBuffer(num: bigint, endian: 'be' | 'le') {
const bytes: number[] = [];
while (num > 0) {
bytes.push(Number(num & 0xffn));
num = num >> 8n;
}
return Buffer.from(endian === 'be' ? bytes.reverse() : bytes);
}
function bufferToBigInt(bytes: Buffer, endian: 'be' | 'le') {
let num = 0n;
for (let i = 0; i < bytes.length; i++) {
num += BigInt(bytes[i]) << (8n * BigInt(endian === 'le' ? bytes.length - 1 - i : i));
}
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment