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]);
        }      
    }

 

 

測試正常。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM