二進制 0/1 序列過長難讀,十六進制每字節僅 2 字符(00-FF),是「查看加密數據、分析協議包、調試編碼」的標準視圖,也是 UE、WinHex 等十六進制編輯器的核心顯示模式。
Java byte 範圍 -128~127,直接轉 int 會符號擴展(如 byte -42 → int -42,而非 214)。
& 0xFF 強制無符號化int unsigned = byteVal & 0xFF; // -42 → 214
原理:0xFF 二進制全 1,按位與保留低 8 位,高位補 0,實現無符號擴展。
+ 0x100 保證兩位輸出String hex = Integer.toString((byteVal & 0xFF) + 0x100, 16).substring(1);
// 0x0A → "0a" 而非 "a"
+ 0x100 相當於在高位加 1,確保至少 3 位十六進制,再 substring(1) 切掉最高位,得到標準 2 位輸出。
public class HexDump {
public static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(Integer.toString((b & 0xFF) + 0x100, 16).substring(1));
}
return sb.toString();
}
public static byte[] fromHex(String hex) {
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 static void main(String[] args) {
// 驗證 -128~127 全覆蓋
for (int i = -128; i < 128; i++) {
byte b = (byte) i;
System.out.printf("%4d → %s%n", i, toHex(new byte[]{b}));
}
}
}
同理,只需改 toString(val, radix) 的基數:
radix=2,補位 + 0x100 → + 0b1_0000_0000radix=8,補位 + 0x400(八進制 1000)FF D8 FF (JPEG)、89 50 4E 47 (PNG)掌握 byte & 0xFF 去符號、+ 0x100 補位、Integer.toString(..., 16) 轉字符串三步曲,即可輕鬆實現高性能、零依賴的十六進制轉換工具,是 Java 開發處理二進制數據的基本功。