java 接收无符号类型的(Long、int、short)

最近在做一个项目,需要和C++通讯,双方通讯没有采用JNI的方式进行,使用字节序的方式进行进行(字节序就是所谓双方把协议定义好,按顺序进行接收),刚开始测试的时候未注意C++的unsigned int 类型,当一次测试忽然想起,JAVA是有符号的数据类型,最高位表示符号类型那个,如果无符号类型接收有符号的类型int, 那就用LONG,然后发现是错误的,发现高位的32位存在值,低32位是无符号类型INT发过来的值,然后想到一个方法就是对字节进行与和位移的操作,希望以下代码能对大家有用:
public static void main(String args[]){
short anUnsignedByte = 0;
char anUnsignedShort = 0;
long anUnsignedInt = 0;

int firstByte = 0;
int secondByte = 0;
int thirdByte = 0;
int fourthByte = 0;

byte buf[] = getMeSomeData();
// Check to make sure we have enough bytes
if(buf.length < (1 + 2 + 4))
doSomeErrorHandling();
int index = 0;

firstByte = (0x000000FF & ((int)buf[index]))
index++;
anUnsignedByte = (short)firstByte;

firstByte = (0x000000FF & ((int)buf[index]))
secondByte = (0x000000FF & ((int)buf[index+1]))
index = index+2;
anUnsignedShort = (char) (firstByte << 8 | secondByte);

firstByte = (0x000000FF & ((int)buf[index]))
secondByte = (0x000000FF & ((int)buf[index+1]))
thirdByte = (0x000000FF & ((int)buf[index+2]))
fourthByte = (0x000000FF & ((int)buf[index+3]))
index = index+4;
anUnsignedInt = ((long) (firstByte << 24
| secondByte << 16
| thirdByte << 8
| fourthByte))
& 0xFFFFFFFFL;
System.out.println(anUnsignedInt ); //打印出无符号类型用long进行正确接收的值
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值