java中byte数组和int型数组的转换

  读取数据库,读取串口,等等 都是以byte为单位的,所以必须转换成字节想要的数据就必须要转换,再c和C++中的方法用 方法比较简单。但是再java中就比较复杂了,必须写方法去转换

转换方法如下;

 
 //将整型数组转换成byte数组
   public static byte[] IntArrytoByteArry(int [] a)
   {              
        if(a.length == 0) {
            
            return null;
        }
        
         byte[] b = new byte[a.length*4];
         int value =0;
         int offset =0;
       
          for(int i=0;i<a.length;i++)
          {
              
               value = a[i];
               b[i*4+0]=(byte) (value & 0xFF);
               b[i*4+1]=(byte) ((value>> 8) & 0xFF);    
               b[i*4+2]=(byte) ((value >> 16) & 0xFF);
               b[i*4+3]=(byte) ((value >> 24) & 0xFF);                                                               
          }
                                                
         return b;
   }
  
   //将byte数组转换成int数组
   
  
    public static int [] ByteArrytoIntArray(byte[] a)
    {
        
        if((a.length==0) ||(a.length%4 !=0))
        {
            
             return null;
        }
        
        int[] b=new int[a.length/4];
        
        int value  = 0;
        
        for(int i=0;i<a.length/4;i++)
        {
        
            
            //大字节序
//            value =    a[3+i*4] & 0xFF |
//                      (a[2+i*4] & 0xFF) << 8 |
//                      (a[1+i*4] & 0xFF) << 16 |
//                      (a[0+i*4] & 0xFF) << 24;  
            
            //小字节序
            value =    a[0+i*4] & 0xFF |
                      (a[1+i*4] & 0xFF) << 8 |
                      (a[2+i*4] & 0xFF) << 16 |
                      (a[3+i*4] & 0xFF) << 24;  
            
            
            b[i] =value;
        }
        
        
        
        
        
        return b;
    }


         
       

}

测试代码如下

public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a = new int[] {100,500,600,900,800,76};

        byte[] c =Transhfer.IntArrytoByteArry(a);
        for(int i=0;i<c.length;i++)
        {
            System.out.println(c[i]);
        }       
        
        
        
        int[] d =Transhfer.ByteArrytoIntArray(c);
        for(int i=0;i<d.length;i++)
        {
            System.out.println(d[i]);
        }      
    }

测试正常。

要有韧性
原文地址:https://www.cnblogs.com/niuxiaojie521/p/14776859.html