How to convert byte string into Number?
I have a string encoded in Little Endian format (least-significant-byte first), and I want to decode开发者_运维问答 it into a Number. For the encoder, the first bit of the last byte reflects whether the number is positive or negitive. Does anyone know how to do this?
Here's my decoder:
decode:function(str,type){
var num=0;
var len=size(type)-(type.signed?1:0);
var totalBits=0;
for(var i=0;i<len;i++){
num+=(str.charCodeAt(i)<<totalBits));
totalBits+=8;
}
if(type.signed){
var b=str.charCodeAt(size(type)-1);
var neg=(b>=128);
if(neg){
b-=128;
}
num+=b;
num*=(neg?-1:1);
}
return num;
}
Thanks.
It's easier if you read the string from right to left. You could do something like this:
/* decode. assume size(str) > 0 */
function (str,type) {
var len = size(str);
var num = str.charCodeAt(len - 1);
if (type.signed && (num >= 128)) {
num = num - 256;
}
for (var i = (len - 2); i >= 0; i--) {
num = 256 * num + str.charCodeAt(i);
}
return num;
}
精彩评论