如何在java中将UTF-16转换为UTF-32?

时间:2016-04-04 02:41:07

标签: java unicode utf-16 utf-32

我一直在寻找解决方案,但在这个主题上似乎并没有多少。我找到了建议的解决方案:

String unicodeString = new String("utf8 here");
byte[] bytes = String.getBytes("UTF8"); 
String converted = new String(bytes,"UTF16");

从utf8转换为utf16,然而,java并没有处理" UTF32",这使得该解决方案不可行。有没有人知道如何实现这个目标?

3 个答案:

答案 0 :(得分:3)

Java确实处理UTF-32,尝试此测试

    byte[] a = "1".getBytes("UTF-32");
    System.out.println(a.length);

它将显示数组'lentgh = 4

答案 1 :(得分:2)

搜索后我得到了这个工作:

    public static String convert16to32(String toConvert){
        for (int i = 0; i < toConvert.length(); ) {
            int codePoint = Character.codePointAt(toConvert, i);
            i += Character.charCount(codePoint);
            //System.out.printf("%x%n", codePoint);
            String utf32 = String.format("0x%x%n", codePoint);
            return utf32;
        }
        return null;
    }

答案 2 :(得分:1)

public static char[] bytesToHex(byte[] raw) {
    int length = raw.length;
    char[] hex = new char[length * 2];
    for (int i = 0; i < length; i++) {
        int value = (raw[i] + 256) % 256;
        int highIndex = value >> 4;
        int lowIndex = value & 0x0f;
        hex[i * 2 + 0] = kDigits[highIndex];
        hex[i * 2 + 1] = kDigits[lowIndex];
    }
    return hex;
}



byte[] bytearr = converted.getBytes("UTF-32");
System.out.println("With UTF-32 encoding:\t" + String.valueOf(bytesToHex(bytearr)));
System.out.println("With UTF-32 decoding:\t" + new String((bytearr), "UTF-32"));