给定扩展 ASCII 代码点和 Java 中的代码页,找到等效的 Unicode 代码点?
Finding the equivalent Unicode codepoint given an extended ASCII codepoint and a codepage in Java?
我正在尝试编写一种方法,在给定特定代码页的情况下,在 ASCII 中查找相同视觉字符的 Unicode 等效代码点
例如,给定一个字符 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 中完成?
c
实际上不应该是 char
,而是相应编码中的 byte[]
个字节,例如。 windows-1252.
对于这种简单的情况,我们可以自己将 char
包装成 byte[]
。
您需要将这些字节解码为 Java 的 char
类型,它表示 BMP 代码点。那你return对应的
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
我正在尝试编写一种方法,在给定特定代码页的情况下,在 ASCII 中查找相同视觉字符的 Unicode 等效代码点
例如,给定一个字符 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 中完成?
c
实际上不应该是 char
,而是相应编码中的 byte[]
个字节,例如。 windows-1252.
对于这种简单的情况,我们可以自己将 char
包装成 byte[]
。
您需要将这些字节解码为 Java 的 char
类型,它表示 BMP 代码点。那你return对应的
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