Skip to content

Instantly share code, notes, and snippets.

@nlf
Created October 21, 2012 02:38
Show Gist options
  • Save nlf/3925517 to your computer and use it in GitHub Desktop.
Save nlf/3925517 to your computer and use it in GitHub Desktop.
varints
function lshift(num, bits) {
return num * Math.pow(2, bits);
}
function rshift(num, bits) {
return num / Math.pow(2, bits);
}
function encode(num) {
if (num === 0) return new Buffer([0x00]);
var bytes = [];
while (num >= 0x80) {
bytes.push(num | 0x80);
num = rshift(num, 7);
}
bytes.push(num);
return new Buffer(bytes);
}
function decode(varint) {
var nextByte,
result = 0,
bytesRead = 0;
do {
nextByte = varint[bytesRead];
result += lshift((nextByte & 0x7F), (7 * bytesRead));
bytesRead++;
} while (nextByte >= 0x80);
return { num: result, bytes: bytesRead };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment