網絡通訊、二進制協議解析中,頻繁需要將 4 字節 byte[] 與 int 互轉(大端序)。
/** int -> byte[] (大端序) */
public static byte[] intToBytes(int value) {
return new byte[] {
(byte) (value >>> 24),
(byte) (value >>> 16),
(byte) (value >>> 8),
(byte) value
};
}
/** byte[] -> int (大端序,長度必須≥4) */
public static int bytesToInt(byte[] bytes) {
return ((bytes[0] & 0xFF) << 24) |
((bytes[1] & 0xFF) << 16) |
((bytes[2] & 0xFF) << 8) |
(bytes[3] & 0xFF);
}
import java.io.*;
public static byte[] intToBytes2(int value) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(value); // 自動大端序
return baos.toByteArray();
}
public static int bytesToInt2(byte[] bytes) throws IOException {
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
return dis.readInt();
}
public static void main(String[] args) throws IOException {
int val = 0x01020304;
byte[] b1 = intToBytes(val);
byte[] b2 = intToBytes2(val);
System.out.println(Arrays.equals(b1, b2)); // true
System.out.println(bytesToInt(b1) == val); // true
System.out.println(bytesToInt2(b2) == val); // true
}
| 方法 | 耗時 (1000萬次) | 優點 | 缺點 |
|---|---|---|---|
| 位運算 | ~15 ms | 極快、無對象創建 | 手寫易出錯 |
| DataStream | ~120 ms | 標準庫、自動處理端序 | 創建流對象、拋檢查異常 |