Created
February 24, 2025 17:31
-
-
Save cometkim/7ac411e597d620bc2b0e8f37a7846742 to your computer and use it in GitHub Desktop.
Variable Integer (LEB128) encoding with BigInt
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
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