js byte字节流和数字,字符串之间的转换,包含无符和有符之间的转换
程序员文章站
2022-03-18 16:55:14
var NumberUtil={ //byte数组转换为int整数 bytesToInt2:function(bytes, off) { var b3 = bytes[off] & 0xFF; var b2 = bytes[off + 1] & 0xFF; var b1 = bytes[off + ......
var numberutil={
//byte数组转换为int整数
bytestoint2:function(bytes, off) {
var b3 = bytes[off] & 0xff;
var b2 = bytes[off + 1] & 0xff;
var b1 = bytes[off + 2] & 0xff;
var b0 = bytes[off + 3] & 0xff;
return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
},
//byte数组转换为无符号short整数
byte2tounsignedshort:function(bytes, off) {
var high = bytes[off + 1];
var low = bytes[off];
return (high << 8 & 0xff00) | (low & 0xff);
},
//byte数组转字符串
bytetostring:function(arr) {
if (typeof arr === 'string') {
return arr;
}
var str = '',
_arr = arr;
for (var i = 0; i < _arr.length; i++) {
var one = _arr[i].tostring(2),
v = one.match(/^1+?(?=0)/);
if (v && one.length == 8) {
var byteslength = v[0].length;
var store = _arr[i].tostring(2).slice(7 - byteslength);
for (var st = 1; st < byteslength; st++) {
store += _arr[st + i].tostring(2).slice(2);
}
str += string.fromcharcode(parseint(store, 2));
i += byteslength - 1;
} else {
str += string.fromcharcode(_arr[i]);
}
}
return str;
},
//int整数转换为4字节的byte数组
inttobyte4:function(i) {
var targets =[];
targets[0] = (i & 0xff);
targets[1] = (i >> 8 & 0xff);
targets[2] = (i >> 16 & 0xff);
targets[3] = (i >> 24 & 0xff);
return targets;
},
//无符号short转换为2字节的byte数组
unsignedshorttobyte2:function(s){
var targets = [];
targets[1] = (s >> 8 & 0xff);
targets[0] = (s & 0xff);
return targets;
},
//字符串转byte数组
stringtobyte:function(str) {
var bytes = new array();
var len, c;
len = str.length;
for(var i = 0; i < len; i++) {
c = str.charcodeat(i);
if(c >= 0x010000 && c <= 0x10ffff) {
bytes.push(((c >> 18) & 0x07) | 0xf0);
bytes.push(((c >> 12) & 0x3f) | 0x80);
bytes.push(((c >> 6) & 0x3f) | 0x80);
bytes.push((c & 0x3f) | 0x80);
} else if(c >= 0x000800 && c <= 0x00ffff) {
bytes.push(((c >> 12) & 0x0f) | 0xe0);
bytes.push(((c >> 6) & 0x3f) | 0x80);
bytes.push((c & 0x3f) | 0x80);
} else if(c >= 0x000080 && c <= 0x0007ff) {
bytes.push(((c >> 6) & 0x1f) | 0xc0);
bytes.push((c & 0x3f) | 0x80);
} else {
bytes.push(c & 0xff);
}
}
return bytes;
},
//有符int转无符int
int2uint:function(i) {
if (i >= 0)
return i;
else
4294967296 + i;
},
//无符int转有符int
uint2int:function(i) {
if (i <= 2147483647)
return i;
else
return i - 4294967296
},
//有符char转无符char
char2uchar:function(i) {
if (i >= 0)
return i;
else
65535 + i;
},
//无符char转有符char
uchar2char:function(i) {
if (i <= 32767)
return i;
else
return i - 65535
},
//有符byte转无符byte
bytes2ubytes:function(i) {
if (i >= 0)
return i;
else
255 + i;
},
//无符byte转有符byte
ubytes2bytes:function(i) {
if (i <= 127)
return i;
else
return i - 255
}
}
上一篇: 【JAVA SE基础篇】7.变量和常量
下一篇: 你还有B脸笑