java int 获取高四位和低四位,反过来根据高四位和低四位的byte 计算int的值;
问题描述:
int code = 500;
int high = ((code & 0xff00) >> 8);
int low = code & 0x00ff;
System.out.print("high-low: " + high + " " + low);
打印结果:high-low: 1 244 16进制: 0x01 ,0xF4
我要发送的数据就是 byte [] = {0x01,0xF4};
现在接收到 byte[] = {0x12,0xFA};分别是code的高四位和低四位,
我要怎样才能计算出code的值?
求大神给代码,谢谢!
答
我先纠正下你的错误,int最大是4个字节,而500的有效字节是2个字节,如下图:
所以你上面是分别获取500的高8位和低8位,并不是你说的4位
byte [] = {0x01,0xF4}; 其实和你上面反过来即可
//1、向左移动8位,
int height = byte[0] << 8;
//2、确保低位都是0
height &= 0xff00;
//3、高位与低位相加。
int code= height + byte[1] // int code = height | byte[1]
答
byte[] b= {0x12,0xFA};
int i = b[0]*65536+b[1];