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

方法1:使用Integer.toHexString()
public class AsciiToHex {
public static void main(String[] args) {
char asciiChar = 'A'; // ASCII字符
String hex = Integer.toHexString((int) asciiChar).toUpperCase();
System.out.println("ASCII '" + asciiChar + "' 的16进制表示: " + hex);
}
}
输出:
ASCII 'A' 的16进制表示: 41
方法2:格式化输出
public class AsciiToHex {
public static void main(String[] args) {
char asciiChar = 'Z';
String hex = String.format("%02X", (int) asciiChar);
System.out.println("ASCII '" + asciiChar + "' 的16进制表示: " + hex);
}
}
输出:
ASCII 'Z' 的16进制表示: 5A
方法3:转换整个字符串
public class AsciiToHex {
public static String stringToHex(String str) {
StringBuilder hexString = new StringBuilder();
for (char c : str.toCharArray()) {
hexString.append(String.format("%02X", (int) c));
}
return hexString.toString();
}
public static void main(String[] args) {
String text = "Hello";
System.out.println("字符串 '" + text + "' 的16进制表示: " + stringToHex(text));
}
}
输出:
字符串 'Hello' 的16进制表示: 48656C6C6F
方法4:使用字节转换
public class AsciiToHex {
public static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
hexString.append(String.format("%02X", b));
}
return hexString.toString();
}
public static void main(String[] args) {
String text = "Java";
byte[] bytes = text.getBytes();
System.out.println("字符串 '" + text + "' 的16进制表示: " + bytesToHex(bytes));
}
}
输出:

字符串 'Java' 的16进制表示: 4A617661
注意事项
- ASCII字符是7位编码,范围0-127,而Java的char是16位Unicode
- 对于非ASCII字符,这些方法会给出其Unicode码点的16进制表示
- 如果需要处理真正的ASCII字节,应该使用
byte而不是char
方法可以根据具体需求选择使用,方法2和方法3在格式化输出方面更为灵活。
