在 Java 開發中,經常需要將位元組陣列(byte[])轉換為十六進制字串表示,或者反向解析。這在網路傳輸、加密演算法、日誌記錄等場景非常常見。雖然 Apache Commons Codec 提供了現成的 Hex 工具類,但理解其核心實現原理並掌握一個輕量級、無依賴的實現方式同樣重要。
一個位元組佔 8 位,而一個十六進制字符佔 4 位。因此,一個位元組可以拆分為高 4 位和低 4 位,分別對應一個十六進制字符。轉換時,透過位運算 (b >>> 4) & 0x0F 取高四位,b & 0x0F 取低四位,再映射到字符陣列 {'0'-'9', 'a'-'f'} 或 {'0'-'9', 'A'-'F'} 即可。
public class HexUtil {
private static final char[] DIGITS_LOWER = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
private static final char[] DIGITS_UPPER = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
/** 位元組陣列轉十六進制字符陣列 */
public static char[] encodeHex(byte[] data) {
return encodeHex(data, true);
}
public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
protected static char[] encodeHex(byte[] data, char[] toDigits) {
int l = data.length;
char[] out = new char[l << 1];
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
/** 位元組陣列轉十六進制字串 */
public static String encodeHexStr(byte[] data) {
return new String(encodeHex(data));
}
public static String encodeHexStr(byte[] data, boolean toLowerCase) {
return new String(encodeHex(data, toLowerCase));
}
/** 十六進制字符陣列轉位元組陣列 */
public static byte[] decodeHex(char[] data) {
int len = data.length;
if ((len & 0x01) != 0) {
throw new IllegalArgumentException("十六進制字符長度必須為偶數");
}
byte[] out = new byte[len >> 1];
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f |= toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
protected static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new IllegalArgumentException("非法十六進制字符: " + ch + " at index " + index);
}
return digit;
}
// 測試主方法
public static void main(String[] args) {
String src = "HelloWorld!";
String encoded = encodeHexStr(src.getBytes(), false); // 大寫
String decoded = new String(decodeHex(encoded.toCharArray()));
System.out.println("原始字串: " + src);
System.out.println("編碼結果: " + encoded);
System.out.println("解碼結果: " + decoded);
}
}
>>> 無符號右移和 & 位與操作,避免了除法和取模的性能開銷。DIGITS_LOWER 和 DIGITS_UPPER 實現,無需字串操作。IllegalArgumentException。專案若已引入 commons-codec,優先使用 org.apache.commons.codec.binary.Hex;若為獨立模組或對依賴敏感,可直接複製上述 HexUtil 類使用。