byte數組和int之間相互轉化的方法


Java中byte數組和int類型的轉換,在網絡編程中這個算法是最基本的算法,我們都知道,在socket傳輸中,發送者接收的數據都是byte數組,但是int類型是4個byte組成的,如何把一個整形int轉換成byte數組,同時如何把一個長度為4的byte數組轉換成int類型。

方法一:

public static byte[] intToByteArray(int i) {  
  byte[] result = new byte[4];  
  // 由高位到低位  
  result[0] = (byte) ((i >> 24) & 0xFF);  
  result[1] = (byte) ((i >> 16) & 0xFF);  
  result[2] = (byte) ((i >> 8) & 0xFF);  
  result[3] = (byte) (i & 0xFF);  
  return result;  
}  
public static int byteArrayToInt(byte[] bytes) {  
    int value = 0;  
    // 由高位到低位  
    for (int i = 0; i < 4; i++) {  
      int shift = (4 - 1 - i) * 8;  
      value += (bytes[i] & 0x000000FF) << shift;// 往高位游  
    }  
    return value;  
} 

方法二:

此方法可以對string類型,float類型,char類型等 來與 byte類型的轉換

public static void main(String[] args) {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    DataOutputStream dos = new DataOutputStream(baos);  
    try {  
        // int轉換byte數組  
        dos.writeByte(-12);  
        dos.writeLong(12);  
        dos.writeChar('1');  
        dos.writeFloat(1.01f);  
        dos.writeUTF("好");  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
  
    byte[] aa = baos.toByteArray();  
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());  
    DataInputStream dis = new DataInputStream(bais);  
    // byte轉換int  
    try {  
         System.out.println(dis.readByte());  
         System.out.println(dis.readLong());  
         System.out.println(dis.readChar());  
         System.out.println(dis.readFloat());  
         System.out.println(dis.readUTF());  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
    try {  
        dos.close();  
        dis.close();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
}
public class RandomUtil {
  public static byte[] intToByteArray(int i) {  
      byte[] result = new byte[4];  
      // 由高位到低位  
      result[0] = (byte) ((i >> 24) & 0xFF);  
      result[1] = (byte) ((i >> 16) & 0xFF);  
      result[2] = (byte) ((i >> 8) & 0xFF);  
      result[3] = (byte) (i & 0xFF);  
      return result;  
  }  

  public static void main(String[] args) {
     int v = 123456;
    byte[] bytes = ByteBuffer.allocate(4).putInt(v).array();
     for (byte t : bytes) {
        System.out.println(t);
     }
    System.out.println("----- 分割線 -------");
    byte[] bytes2 = intToByteArray(v);
    for (byte t : bytes2) {
      System.out.println(t);
    }
  }
}

 


免責聲明!

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



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