Skip to content

Instantly share code, notes, and snippets.

@cometkim
Created February 24, 2025 17:31
Show Gist options
  • Save cometkim/7ac411e597d620bc2b0e8f37a7846742 to your computer and use it in GitHub Desktop.
Save cometkim/7ac411e597d620bc2b0e8f37a7846742 to your computer and use it in GitHub Desktop.
Variable Integer (LEB128) encoding with BigInt
export function encode(value) {
const long = BigInt(value);
const result = [];
let shift = 0n;
while (true) {
const number = Number(BigInt.asUintN(7, long >> shift));
if (number) {
result.push(number);
shift += 7n;
} else {
break;
}
}
for (let i = 0, len = result.length - 1; i < len; i++) {
result[i] += 128;
}
return new Uint8Array(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment