核心需求
- 字串 → 十六進制(Hex)
- 十六進制 → 字串
- 支援中文等多位元組字元(UTF-8)
- Byte 陣列格式化輸出(如
0x2B 0x44)
方案一:標準庫 Integer.toHexString + 手動補零
public class HexUtils {
// 字串 → Hex (UTF-8)
public static String encode(String str) {
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(String.format("%02X", b)); // 大寫、兩位、不足補零
}
return sb.toString();
}
// Hex → 字串 (UTF-8)
public static String decode(String hex) {
int len = hex.length();
byte[] bytes = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
bytes[i / 2] = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
}
return new String(bytes, StandardCharsets.UTF_8);
}
// Byte[] → 格式化 Hex 字串(含空格、大寫)
public static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
return sb.toString().trim();
}
// Hex 字串 → Byte[](每兩字元一 byte)
public static byte[] hexStringToBytes(String hex) {
hex = hex.replaceAll("\\s+", ""); // 移除空格
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return bytes;
}
}
方案二:查表法(效能更高、無格式化開銷)
public class HexUtilsFast {
private static final char[] HEX = "0123456789ABCDEF".toCharArray();
public static String encode(byte[] bytes) {
char[] chars = new char[bytes.length * 2];
for (int i = 0, j = 0; i < bytes.length; i++) {
chars[j++] = HEX[(bytes[i] & 0xF0) >>> 4];
chars[j++] = HEX[bytes[i] & 0x0F];
}
return new String(chars);
}
public static byte[] decode(String hex) {
hex = hex.replaceAll("\\s+", "");
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
int high = Character.digit(hex.charAt(i * 2), 16);
int low = Character.digit(hex.charAt(i * 2 + 1), 16);
bytes[i] = (byte) ((high << 4) | low);
}
return bytes;
}
}
方案三:Apache Commons Codec / Spring / Guava 一行搞定
// Commons Codec
String hex = Hex.encodeHexString(bytes);
byte[] bytes = Hex.decodeHex(hex.toCharArray());
// Spring Framework
String hex = org.springframework.util.StringUtils.bytesToHexString(bytes);
// 注:Spring 5.3+ 提供 HexFormat (Java 17+)
// Java 17+ 標準庫
String hex = java.util.HexFormat.of().formatHex(bytes);
byte[] bytes = java.util.HexFormat.of().parseHex(hex);
實戰:列印 Byte 陣列供除錯
public static void printHex(String hint, byte[] data) {
System.out.print(hint + ": ");
for (byte b : data) {
System.out.printf("%02X ", b);
}
System.out.println();
}
// 輸出範例:CMD: 2B 44 EF D9
測試驗證
public static void main(String[] args) {
String original = "中文測試123";
String hex = HexUtils.encode(original);
String decoded = HexUtils.decode(hex);
System.out.println("原文:" + original);
System.out.println("Hex:" + hex);
System.out.println("解碼:" + decoded);
System.out.println("驗證:" + original.equals(decoded)); // true
}
總結建議
| 場景 | 推薦做法 |
| 一般專案、可引入第三方 | Apache Commons Codec / Spring Utils |
| 無依賴、追求效能 | 查表法 HexUtilsFast |
| Java 17+ 環境 | 標準 java.util.HexFormat |
| 教學、理解原理 | 手工 String.format("%02X") 或位運算 |