專案開發中頻繁遇到位元組陣列與十六進制字串互轉需求:網路協定解析、加密演算法輸出、日誌記錄等。本文提供一個生產就緒的工具類,涵蓋四大核心場景,代碼經過實戰驗證,可直接納入專案公共庫。
| 方法 | 用途 | 輸入 | 輸出 |
|---|---|---|---|
printHexString | 控制台輸出十六進制 | 提示字串 + byte[] | void |
bytesToHexString | 位元組陣列轉十六進制字串 | byte[] | String (大寫,無分隔) |
uniteBytes | 兩 ASCII 字符合併為一位元組 | byte high, byte low | byte |
hexStringToBytes | 十六進制字串轉位元組陣列 | String (長度為 16) | byte[8] |
public static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) sb.append('0');
sb.append(hex.toUpperCase());
}
return sb.toString();
}
關鍵點:b & 0xFF 將有符號位元組轉為無符號整數(0-255),避免負數導致的符號擴展;StringBuilder 替代字串拼接,提升效能。
public static byte[] hexStringToBytes(String hex) {
int len = hex.length();
byte[] result = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
result[i / 2] = uniteBytes(
(byte) hex.charAt(i),
(byte) hex.charAt(i + 1)
);
}
return result;
}
private static byte uniteBytes(byte high, byte low) {
int h = Character.digit((char) high, 16);
int l = Character.digit((char) low, 16);
return (byte) ((h << 4) | l);
}
改進點:原版固定輸出 8 位元組,新版支援任意偶數長度;使用 Character.digit 替代 Byte.decode,效能更高且無異常拋出開銷。
byte[] data = {0x2B, 0x44, (byte)0xEF, (byte)0xD9};
String hex = bytesToHexString(data); // "2B44EFD9"
byte[] restored = hexStringToBytes(hex); // 還原原陣列
Hex 類:Hex.encodeHexString(bytes) / Hex.decodeHex(hex.toCharArray()),經過大規模生產驗證java.util.HexFormat:HexFormat.of().formatHex(bytes) / HexFormat.of().parseHex(hex)