How can I convert UTF-16 to UTF-32 in java?

六眼飞鱼酱① 提交于 2019-12-04 11:48:27

Java does handle UTF-32, try this test

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

it will show that arrays' lentgh = 4

after searching I got this to work:

    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;
    }
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"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!