一般无需java来处理byte字节的数据转成 int , C语言更适合干这事. 但是无奈遇到了这种需求.

网上百度了一小部分代码, 发现好多错误代码… 干脆自己手写了一遍…

byte[]数据的格式协议文档如下:

java byte[]转int和double_java

先上使用代码

byte[] hex = Base64.getDecoder().decode(data);
int head = Read3Bytes(hex, 0) ;// 3个字节 1b7273
if(head != 1798771) // 十进制 1798771 ==== 16进制 0x1b7273
{
throw new Exception("不可识别的数据包");
}
// 数据长度是
int datalength = Read1Bytes(hex, 3); //1字节 此数据后面所带的有效数据长度
// 命令字
int cmd = Read1Bytes(hex, 4); ; // 命令字 0:服务器通过get获取 1:开门 2:关门
//温度
int wendu = Read3Bytes(hex, 5) ;// 3个字节 0x01+2字节温度数据
//湿度
int shidu = Read2Bytes(hex, 8);// 2个字节 2字节湿度数据
//距离: 0x02+2字节距离数据
int juli = Read3Bytes(hex, 10);

下面是主要代码

//循环累加、或运算都可以
public static int Read1Bytes(byte[] bytes,int startindex){
return bytes[startindex] ;
}

public static int Read2Bytes(byte[] bytes,int startindex){
return bytes[startindex] << 8
| (bytes[startindex + 1] << 0) ;


}
public static int Read3Bytes(byte[] bytes,int startindex){
return bytes[startindex] << 16
| (bytes[startindex + 1] <<8)
| (bytes[startindex + 2] <<0);

}
public static int Read4Bytes(byte[] bytes,int startindex){
return bytes[startindex] << 24
| (bytes[startindex + 1] << 16)
| (bytes[startindex + 2] << 8)
| (bytes[startindex + 3] << 0);

}

public static double Read5Bytes(byte[] bytes,int startindex){
return bytes[startindex] << 32
| (bytes[startindex + 1] << 24)
| (bytes[startindex + 2] << 16)
| (bytes[startindex + 3] << 8)
| (bytes[startindex + 4] << 0);

}

public static double Read6Bytes(byte[] bytes,int startindex){
return bytes[startindex] << 40
| (bytes[startindex + 1] << 32)
| (bytes[startindex + 2] << 24)
| (bytes[startindex + 3] << 16)
| (bytes[startindex + 4] << 8)
| (bytes[startindex + 5] << 0);

}

public static double Read7Bytes(byte[] bytes,int startindex){
return bytes[startindex] << 48
| (bytes[startindex + 1] << 40)
| (bytes[startindex + 2] << 32)
| (bytes[startindex + 3] << 24)
| (bytes[startindex + 4] << 16)
| (bytes[startindex + 5] << 8)
| (bytes[startindex + 6] << 0);

}

public static double Read8Bytes(byte[] bytes,int startindex){
return bytes[startindex] << 56
| (bytes[startindex + 1] << 48)
| (bytes[startindex + 2] << 40)
| (bytes[startindex + 3] << 32)
| (bytes[startindex + 4] << 24)
| (bytes[startindex + 5] << 16)
| (bytes[startindex + 6] << 8)
| (bytes[startindex + 7] << 0);

}