0

What I'm trying to do is generate an array of chars that represent certain ASCII values in a certain ISO/IEC charset. Let's say, if I'm intersted in ASCII values 211-217 of ISO/IEC 8859-7 charset then the result should be { Σ, Τ, Υ, Φ, Χ, Ψ, Ω }. I tried this:

for (int i = 211; i <= 217; i++) {
    System.out.println(String.valueOf((char)i));
}

But the results are based on the default system charset.

4

2 回答 2

4

您不能将特定编码中的单个字符代码char直接转换为 s,因此您需要使用byte[]toString转换。由于 ISO-8859-7 是单字节编码,每个字符代码对应一个byte

Charset cs = Charset.forName("ISO-8859-7");
for (int i = 211; i <= 217; i++) {
    String s = new String(new byte[] { (byte) i }, cs)
    System.out.println(
        String.format("Character %s, codepoint %04X", s, (int) s.charAt(0)));
} 

编辑:使用上面给出的输出格式,您可以确保按照ISO-8859-7的规定正确解码 Unicode 代码点。如果您仍然看到?s 而不是字符,则说明输出有问题 - 您的控制台不支持这些字符。

检查结果System.getProperty("file.encoding")- 它应该是某种 Unicode(UTF-8等)。如果您从 IDE 运行代码,请检查其配置以了解控制台编码设置。

于 2012-09-13T19:13:34.723 回答
1

你的问题并不完全清楚。我认为您的意思是您有 ISO-8859-7 编码的字符,并且您想将它们转换为 Java 字符(这是 UTF-16 编码的 Unicode 点)。

在这种情况下,试试这个:

byte[] encoded = new byte[7];
for (int e = 211; e <= 217; ++e) 
  encoded[e - 211] = (byte) e;
String s = new String(encoded, "ISO-8859-7");
for (int idx = 0; idx < s.length(); ++idx) 
  System.out.println(s.charAt(idx));
于 2012-09-13T19:14:53.130 回答