bearcat-buffer
Version:
bearcat buffer
67 lines (54 loc) • 1.17 kB
JavaScript
var Codec = {};
/**
* [encode an uInt32, return a array of bytes]
* @param {[integer]} num
* @return {[array]}
*/
Codec.encodeUInt32 = function(num) {
var n = parseInt(num);
if (isNaN(n) || n < 0) {
return null;
}
var result = [];
do {
var tmp = n % 128;
var next = Math.floor(n / 128);
if (next !== 0) {
tmp = tmp + 128;
}
result.push(tmp);
n = next;
} while (n !== 0);
return result;
};
/**
* [encode a sInt32, return a byte array]
* @param {[sInt32]} num The sInt32 need to encode
* @return {[array]} A byte array represent the integer
*/
Codec.encodeSInt32 = function(num) {
var n = parseInt(num);
if (isNaN(n)) {
return null;
}
n = n < 0 ? (Math.abs(n) * 2 - 1) : n * 2;
return Codec.encodeUInt32(n);
};
Codec.decodeUInt32 = function(bytes) {
var n = 0;
for (var i = 0; i < bytes.length; i++) {
var m = parseInt(bytes[i]);
n = n + ((m & 0x7f) * Math.pow(2, (7 * i)));
if (m < 128) {
return n;
}
}
return n;
};
Codec.decodeSInt32 = function(bytes) {
var n = this.decodeUInt32(bytes);
var flag = ((n % 2) === 1) ? -1 : 1;
n = ((n % 2 + n) / 2) * flag;
return n;
};
module.exports = Codec;