網路協定、二進制協定、加密演算常需在 byte、int、hex、String 間轉換。本文提供生產級工具類,涵蓋 8 種核心轉換場景,代碼可直接落地。
public static int byte2Int(byte b) { return (int) b; }
public static byte int2Byte(int i) { return (byte) i; }
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();
}
關鍵: b & 0xFF 將有號 byte 轉為無號 int(0-255),再取十六進制。
public static byte[] hexString2Bytes(String hex) {
if (hex == null || hex.isEmpty() || hex.length() % 2 != 0) return null;
hex = hex.toUpperCase();
byte[] result = new byte[hex.length() / 2];
for (int i = 0; i < result.length; i++) {
int high = "0123456789ABCDEF".indexOf(hex.charAt(2 * i));
int low = "0123456789ABCDEF".indexOf(hex.charAt(2 * i + 1));
result[i] = (byte) ((high << 4) | low);
}
return result;
}
public static String bytes2String(byte[] bytes) throws Exception {
return new String(bytes, StandardCharsets.UTF_8); // 明確指定編碼
}
public static byte[] string2Bytes(String str) {
return str.getBytes(StandardCharsets.UTF_8);
}
public static String hex2String(String hex) throws Exception {
return bytes2String(hexString2Bytes(hex));
}
public static String string2HexString(String str) throws Exception {
return bytes2HexString(string2Bytes(str));
}
public static void main(String[] args) throws Exception {
byte b1 = 45;
System.out.println("1. byte→int: " + byte2Int(b1)); // 45
int i = 89;
System.out.println("2. int→byte: " + int2Byte(i)); // 89
byte[] arr = {(byte)0xFF, (byte)0x5F, 6, (byte)0x5A};
System.out.println("3. bytes→Hex: " + bytes2HexString(arr)); // FF5F065A
String hex = "1DA47C";
System.out.println("4. Hex→bytes: " + Arrays.toString(hexString2Bytes(hex))); // [29, -92, 124]
System.out.println("5. bytes→String: " + bytes2String(arr)); // 亂碼(非文本)
System.out.println("6. String→bytes: " + Arrays.toString(string2Bytes(hex))); // [49, 68, 65, 52, 55, 67]
System.out.println("7. Hex→String: " + hex2String(hex)); // 非可見字元
System.out.println("8. String→Hex: " + string2HexString("Hello!")); // 48656C6C6F21
}
1. byte→int: 45 2. int→byte: 89 3. bytes→Hex: FF5F065A 4. Hex→bytes: [29, -92, 124] 5. bytes→String: ?_Z 6. String→bytes: [49, 68, 65, 52, 55, 67] 7. Hex→String: ?| 8. String→Hex: 48656C6C6F21
Base64.getEncoder().encodeToString(bytes) / getDecoder().decode(str)(JDK 8+)。ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).getInt()。toHexString。收藏此工具類,進制轉換不再手寫 Bug。