Created
October 21, 2012 02:38
-
-
Save nlf/3925517 to your computer and use it in GitHub Desktop.
varints
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
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