int型数据转成byte数据时出现的问题

  由于 byte 的表示范围是 -128 127 ,如果使用下面方法转换将会发生致命的错误:

int num = 40000;

byte first = num/256;

byte second = num%256;

这样,只要firstsecond超过127,就会溢出,从而合并起来的int数值会和原数值不一致。

 

int input2 = 130;

byte a3 = (byte) input2;

input2 = a3;

System.out.println(input2);

对于上述代码,结果为-126,而不是开始的130,也是溢出的问题,所以一定要注意。

 

解决方法:

第一种:较为不彻底,对于正整数来说,可以除以127,从而使byte不会溢出

第二种:转化的时候按位操作,从而不使用强制转化损失精度:

// iSource转为长度为iArrayLenbyte数组,字节数组的低位是整型的低字节位

public static byte[] toByteArray(int iSource, int iArrayLen)

 {

         byte[] bLocalArr = new byte[iArrayLen];

         for ( int i = 0; (i < 4) && (i < iArrayLen); i++)

         {

                   bLocalArr[i] = (byte)( iSource>>8*i & 0xFF );

         }

         return bLocalArr;

}  

// byte数组bRefArr转为一个整数,字节数组的低位是整型的低字节位

public static int toInt(byte[] bRefArr)

 {

         int iOutcome = 0;

         byte bLoop;

        

         for ( int i =0; i<4 ; i++)

         {

                   bLoop = bRefArr[i];

                   iOutcome+= (bLoop & 0xFF) << (8 * i);

         }

         return iOutcome;

}

你可能感兴趣的:(int型数据转成byte数据时出现的问题)