Skip to content

Instantly share code, notes, and snippets.

@GramThanos
Last active August 30, 2021 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GramThanos/a828c5dea417b0db72f50f5696581c9d to your computer and use it in GitHub Desktop.
Save GramThanos/a828c5dea417b0db72f50f5696581c9d to your computer and use it in GitHub Desktop.
Convert Integer to Variable-Length Quantity (VLQ) in JavaScript
// Integer to variable-length quantity (VLQ)
// This is partialy used by ASN.1 for OBJECT IDENTIFIERS
let intToVQL = function(n) {
// If simple form, just return (for simplecity)
// Next line can be removed and the results will be the same
if (n < 128) return new Uint8Array([n]);
// Initial array of bytes
let value = [];
// Convert number to array of bits
n = n.toString(2);
// Pad bits with zero to have a length multiple of 7
while (n.length % 7 != 0) n = '0' + n;
// Split stream to groups of 7 bits
n = n.match(/.{1,7}/g);
// For each group add bit 1 infort of the group exept from the last one
// then convert it back to number and push it into our array
for (let i = 0; i < n.length; i++) {
value.push(parseInt((i < n.length - 1 ? '1' : '0') + n[i], 2));
}
// Convert to byte array and return
return new Uint8Array(value);
}
// Resources used to learn about the format
// https://stackoverflow.com/questions/5929050/how-does-asn-1-encode-an-object-identifier
// https://en.wikipedia.org/wiki/Variable-length_quantity
// https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier?redirectedfrom=MSDN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment