Skip to content

Instantly share code, notes, and snippets.

@silentrob
Created June 16, 2010 04:25
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 silentrob/440159 to your computer and use it in GitHub Desktop.
Save silentrob/440159 to your computer and use it in GitHub Desktop.
// Using JavaScript (node.js) to Read Variable Length Quantity
// See - http://en.wikipedia.org/wiki/Variable-length_quantity for more information
Utils = {}
Utils.arrayToHex = function(ar) {
for (var i=0;i<ar.length;i++) {
ar[i] = (ar[i].toString(16) == 0) ? "00" : ar[i].toString(16);
}
return "0x" + ar.join('');
}
Utils.readVarLen = function(val) {
var buffer = [];
buffer.push((val & 0x7F));
val = (val >> 7)
while (val > 0) {
buffer.push(0x80 + (val & 0x7f))
val = (val >> 7)
}
return Utils.arrayToHex(buffer.reverse());
}
sys.puts(Utils.readVarLen(0x00000000));
sys.puts(Utils.readVarLen(0x00000040));
sys.puts(Utils.readVarLen(0x00000080));
sys.puts(Utils.readVarLen(0x00004000));
sys.puts(Utils.readVarLen(0x00003FFF));
sys.puts(Utils.readVarLen(0x0FFFFFFF));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment