Last active
November 30, 2019 03:13
-
-
Save maca134/3cf54a36ff60220c50a11aee9fa22847 to your computer and use it in GitHub Desktop.
BigInt to Buffer and Buffer to BigInt Nodejs
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
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