以编程方式将Unicode转换为转义的Unicode

时间:2017-01-04 13:59:31

标签: java android unicode

我需要弄清楚将Unicode值转换为转义代码的方法。例如,将0x1f604转换为"\uD83D\uDE04"

1 个答案:

答案 0 :(得分:1)

您似乎正在寻找一种转义,首先将Unicode代码点(32位整数值)转换为UTF-16编码(多个16位值),这是Java在内部用于字符串的编码。

然后,每个16位值都使用Java或Javascript中的转义语法。

public static String encodeCodepoint(int codePoint) {

    char[] chars = Character.toChars(codePoint);
    StringBuilder sb = new StringBuilder();
    for (char ch : chars) {
        sb.append(String.format("\\u%04X", (int)ch));
    }
    return sb.toString();
}

以下代码:

System.out.println(encodeCodepoint(0x1f604));

输出:

\uD83D\uDE04