首页 > 解决方案 > 给定扩展的 ASCII 代码点和 Java 中的代码页,找到等效的 Unicode 代码点?

问题描述

我正在尝试编写一种方法来查找给定特定代码页的 ASCII 中相同视觉字符的 Unicode 中的等效代码点

例如,给定一个字符 say char c = 128,它在 Windows-1252 代码页中是“€”,运行该方法

int result = asUnicode(c, "windows-1252")

应该给出8364或相同char c = 128的,在 Windows-1251 代码页中是 'Ђ',运行方法

int result = asUnicode(c, "windows-1251")

应该给1026

如何在 Java 中做到这一点?

标签: javaunicodecharacter-encodingascii

解决方案


c实际上不应该是 a char,而是byte[]相应编码中的 a 字节,例如。窗户-1252。

对于这种简单的情况,我们可以将其包装char成一个byte[]我们自己。

您需要将这些字节解码为char代表 BMP 代码点的 Java 类型。然后你返回相应的。

public static int asUnicode(char c, String charset) throws Exception {
    CharBuffer result = Charset.forName(charset).decode(ByteBuffer.wrap(new byte[] { (byte) c }));
    int unicode;
    char first = result.get();
    if (Character.isSurrogate(first)) {
        unicode = Character.toCodePoint(first, result.get());
    } else {
        unicode = first;
    }
    return unicode;
}

以下

public static void main(String[] args) throws Exception {
    char c = 128;
    System.out.println(asUnicode(c, "windows-1252"));
    System.out.println(asUnicode(c, "windows-1251"));
}

印刷

8364
1026

推荐阅读