Java 字符串转16进制
在Java中,将字符串转换为16进制表示有几种常见方法,以下是几种实现方式:

方法1:使用字节转换
public static String stringToHex(String str) {
if (str == null || str.isEmpty()) {
return "";
}
StringBuilder hexString = new StringBuilder();
for (char c : str.toCharArray()) {
hexString.append(String.format("%02x", (int) c));
}
return hexString.toString();
}
// 使用示例
String original = "Hello";
String hex = stringToHex(original); // 输出: "48656c6c6f"
方法2:使用getBytes()和BigInteger
import java.math.BigInteger;
public static String stringToHex(String str) {
if (str == null || str.isEmpty()) {
return "";
}
byte[] bytes = str.getBytes();
BigInteger bigInteger = new BigInteger(1, bytes);
return bigInteger.toString(16);
}
// 使用示例
String original = "Hello";
String hex = stringToHex(original); // 输出: "48656c6c6f"
方法3:处理中文等多字节字符
如果需要处理包含中文等多字节字符的字符串,建议使用UTF-8编码:
import java.nio.charset.StandardCharsets;
public static String stringToHex(String str) {
if (str == null || str.isEmpty()) {
return "";
}
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
}
// 使用示例
String original = "你好";
String hex = stringToHex(original); // 输出: "e4bda0e5a5bd"
方法4:16进制转回字符串
如果需要将16进制字符串转回原始字符串:
public static String hexToString(String hex) {
if (hex == null || hex.isEmpty()) {
return "";
}
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
int index = i * 2;
int j = Integer.parseInt(hex.substring(index, index + 2), 16);
bytes[i] = (byte) j;
}
return new String(bytes);
}
// 使用示例
String hex = "48656c6c6f";
String original = hexToString(hex); // 输出: "Hello"
注意事项
- 字符编码很重要,特别是处理非ASCII字符时,建议明确指定编码(如UTF-8)
- 方法1和方法2在处理ASCII字符时结果相同,但方法3更适合多语言文本
- 16进制字符串长度通常是原始字符串长度的2倍(每个字节用2个16进制字符表示)
选择哪种方法取决于你的具体需求和输入字符串的特性。

