1. 程式人生 > >java中byte陣列與int型別的轉換(兩種方式)

java中byte陣列與int型別的轉換(兩種方式)

java中byte陣列與int型別的轉換,在網路程式設計中這個演算法是最基本的演算法,我們都知道,在socket傳輸中,傳送、者接收的資料都是 byte陣列,但是int型別是4個byte組成的,如何把一個整形int轉換成byte陣列,同時如何把一個長度為4的byte陣列轉換為int型別。下面有兩種方式。

  1. publicstaticbyte[] int2byte(int res) {  
  2. byte[] targets = newbyte[4];  
  3. targets[0] = (byte) (res & 0xff);// 最低位 
  4. targets[1] = (byte) ((res >> 
    8) & 0xff);// 次低位 
  5. targets[2] = (byte) ((res >> 16) & 0xff);// 次高位 
  6. targets[3] = (byte) (res >>> 24);// 最高位,無符號右移。 
  7. return targets;   
  8. }   
  1. publicstaticint byte2int(byte[] res) {   
  2. // 一個byte資料左移24位變成0x??000000,再右移8位變成0x00??0000 
  3. int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00// | 表示安位或 
  4. | ((res[2] << 24) >>> 8) | (res[3] << 24);   
  5. return targets;   
  6. }   

第二種

  1. publicstaticvoid main(String[] args) {    
  2.         ByteArrayOutputStream baos = new ByteArrayOutputStream();    
  3.         DataOutputStream dos = new DataOutputStream(baos);    
  4.         try {    
  5.             dos.writeByte(4
    );    
  6.             dos.writeByte(1);    
  7.             dos.writeByte(1);    
  8.             dos.writeShort(217);    
  9.           } catch (IOException e) {    
  10.         e.printStackTrace();    
  11.     }    
  12.     byte[] aa = baos.toByteArray();    
  13.     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());    
  14.     DataInputStream dis = new DataInputStream(bais);    
  15.     try {    
  16.         System.out.println(dis.readByte());    
  17.         System.out.println(dis.readByte());    
  18.         System.out.println(dis.readByte());    
  19.         System.out.println(dis.readShort());    
  20.     } catch (IOException e) {    
  21.         e.printStackTrace();    
  22.     }    
  23.     try {    
  24.         dos.close();    
  25.         dis.close();    
  26.     } catch (IOException e) {    
  27.         e.printStackTrace();    
  28.     }    
  29. }