- A+
所属分类:未分类
//小端模式
function BytesToIntLittleEndian(bytes){
var val = 0;
for (var i = bytes.length - 1; i >= 0; i--) {
val += bytes[i];
if (i != 0) {
val = val << 8;
}
}
return val;
}
//小端模式
//number 要转换的整形数值
//length 要转成什么byte数组,规定数组的长度
//如uint16,则lenght=2表示两个字节,转成的byte数组长度是length=2
//如uint32,则lenght=2表示两个字节,转成的byte数组长度是length=4
function IntToBytesLittleEndian(number, length){
var bytes = [];
var i = 0;
do {
bytes[i++] = number & (255);
number = number>>8;
} while ( i < length )
return bytes;
}
//大端模式
function BytesToIntBigEndian(bytes){
var val = 0;
for (var i = 0; i < bytes.length; ++i) {
val += bytes[i];
if (i < bytes.length-1) {
val = val << 8;
}
}
return val;
}
//大端模式
//number 要转换的整形数值
//length 要转成什么byte数组,规定数组的长度
//如uint16,则lenght=2表示两个字节,转成的byte数组长度是length=2
//如uint32,则lenght=2表示两个字节,转成的byte数组长度是length=4
function IntToBytesBigEndian(number, length){
var bytes = [];
var i = length;
do {
bytes[--i] = number & (255);
number = number>>8;
} while (i)
return bytes;
}
//测试小端模式
i = 65537
bs = IntToBytesLittleEndian(i, 4)
console.log(bs)
console.log(BytesToIntLittleEndian(bs))
//测试大端模式
bs = IntToBytesBigEndian(i, 2)
console.log(bs)
console.log(BytesToIntBigEndian(bs))