小俊同学 发表于 2013-1-26 14:41:07

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++;
anUnsignedByte = (short)firstByte;

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

      firstByte = (0x000000FF & ((int)buf))
      secondByte = (0x000000FF & ((int)buf))
      thirdByte = (0x000000FF & ((int)buf))
      fourthByte = (0x000000FF & ((int)buf))
      index = index+4;
anUnsignedInt= ((long) (firstByte << 24
               | secondByte << 16
                        | thirdByte << 8
                        | fourthByte))
                     & 0xFFFFFFFFL;
System.out.println(anUnsignedInt ); //打印出无符号类型用long进行正确接收的值
}
页: [1]
查看完整版本: java 接收无符号类型的(Long、int、short)