Java 中文字符转 ASCII 码
在 Java 中,将中文字符转换为 ASCII 码需要注意几个关键点:
直接转换(不推荐)
直接使用 char 类型转换只能得到 Unicode 编码,而不是传统的 ASCII 码(ASCII 只包含 0-127 的字符):
char chineseChar = '中'; int unicodeValue = (int) chineseChar; // 得到 Unicode 值,如 20013 System.out.println(unicodeValue);
转换为 GBK/GB2312 编码(推荐)
如果需要获取中文字符在 GBK/GB2312 编码下的 ASCII 表示(实际上是字节码),可以使用以下方法:
import java.nio.charset.StandardCharsets;
public class ChineseToAscii {
public static void main(String[] args) {
String chineseStr = "中文";
// 转换为 GBK 编码的字节数组
byte[] gbkBytes = chineseStr.getBytes(StandardCharsets.GBK);
// 将每个字节转换为十六进制表示
for (byte b : gbkBytes) {
System.out.printf("%02X ", b); // 输出 D6 D0 BB AA
}
}
}
转换为 Unicode 转义序列
如果需要将中文字符转换为 Unicode 转义序列(如 \u4E2D):
public class ChineseToUnicode {
public static void main(String[] args) {
String chineseStr = "中文";
StringBuilder unicodeBuilder = new StringBuilder();
for (char c : chineseStr.toCharArray()) {
unicodeBuilder.append(String.format("\\u%04X", (int) c));
}
System.out.println(unicodeBuilder.toString()); // 输出 \u4E2D\u6587
}
}
注意事项
- ASCII 码范围:传统 ASCII 码只包含英文字母、数字和符号(0-127),无法直接表示中文字符
- 编码选择:GBK 是中文常用的编码,UTF-8 是更通用的编码
- 字节表示:中文字符在 GBK 中通常占 2 个字节,在 UTF-8 中占 3 个字节
完整示例:将中文字符串转换为 GBK 编码的十六进制表示
import java.nio.charset.StandardCharsets;
public class ChineseToHex {
public static void main(String[] args) {
String text = "你好世界";
byte[] gbkBytes = text.getBytes(StandardCharsets.GBK);
System.out.println("GBK 编码的十六进制表示:");
for (byte b : gbkBytes) {
System.out.printf("%02X ", b);
}
// 输出: C4 E3 BA C3 CA A0 CA A0
}
}
根据您的具体需求,可以选择最适合的方法来处理中文字符到 ASCII 相关编码的转换。
