在 Java 開發中,進制轉換是基礎且高頻的操作,特別涉及網絡通訊、文件處理、加密算法等場景。本文系統整理 byte、int、十六進制字符串、普通字符串之間的互相轉換方法,附帶可直接使用的工具類代碼。
// byte → int(保留低 8 位)
public static int byte2Int(byte b) { return b & 0xFF; }
// int → byte(截取低 8 位)
public static byte int2Byte(int i) { return (byte) i; }
注意:Java byte 是有符號的(-128~127),直接強轉會保留符號位,通常配合 & 0xFF 取無符號值。
public static String bytes2HexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) sb.append('0');
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static byte[] hexString2Bytes(String hex) {
if (hex == null || hex.isEmpty() || hex.length() % 2 != 0) return null;
hex = hex.toUpperCase();
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
int high = "0123456789ABCDEF".indexOf(hex.charAt(2 * i));
int low = "0123456789ABCDEF".indexOf(hex.charAt(2 * i + 1));
bytes[i] = (byte) ((high << 4) | low);
}
return bytes;
}
// byte[] → String(指定編碼)
public static String bytes2String(byte[] bytes) throws Exception {
return new String(bytes, "UTF-8");
}
// String → byte[]
public static byte[] string2Bytes(String s) {
return s.getBytes("UTF-8");
}
bytes2String(hexString2Bytes(hex))bytes2HexString(string2Bytes(str))public class HexUtil {
// 上述所有 static 方法放在此處
// 建議補全異常處理、空值校驗、編碼參數化
}
byte b1 = 45; // 1. byte→int: 45
int i = 89; // 2. int→byte: 89
byte[] arr = {(byte)0xFF, (byte)0x5F, 6, (byte)0x5A};
// 3. byte[]→Hex: FF5F065A
String hex = "1DA47C";
// 4. Hex→byte[]: [29, -92, 124]
// 5. byte[]→String: 亂碼(非文本數據)
// 6. String→byte[]: [49, 68, 65, 52, 55, 67](即 "1DA47C" 的 UTF-8 編碼)
// 7. Hex→String: 控制字符
// 8. String→Hex: 48656C6C6F21("Hello!" 的 UTF-8 Hex)
StringBuilder 而非 + 拼接。Hex 類可簡化代碼:Hex.encodeHexString(bytes)。掌握這套轉換體系,能輕鬆應對網絡協議解析、文件校驗、加密解密等場景。建議將上述方法封裝為項目通用工具類,並編寫單元測試覆蓋邊界情況。