【问题标题】:How can I convert UTF-16 to UTF-32 in java?如何在 Java 中将 UTF-16 转换为 UTF-32?
【发布时间】:2016-07-23 11:20:44
【问题描述】:

我一直在寻找解决方案,但似乎没有太多关于这个主题的内容。我找到了建议的解决方案:

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

然而,对于从 utf8 转换为 utf16,java 不处理“UTF32”,这使得该解决方案不可行。有谁知道如何实现这一目标的任何其他方式?

【问题讨论】:

    标签: java unicode utf-16 utf-32


    【解决方案1】:

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

        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;
        }
    

    【讨论】:

    • 很高兴您找到了可行的解决方案!很抱歉没有遵守我的承诺:P 我编写了我的代码,但遇到了无法在其他系统上重现的奇怪问题。我的想法也涉及使用codePointAt(),并且通常非常相似(以防万一你好奇)。
    • String utf32 应该在循环上方声明,return utf32; 应该在循环之后,否则,根本没有循环的意义。
    【解决方案2】:

    Java 确实处理 UTF-32,试试这个测试

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

    它将显示数组的 lentgh = 4

    【讨论】:

    • 那么我将如何进行转换,因为它不适合我?
    • @DanielMedina According to the docs,UTF-32 不能保证在所有系统上都存在;它甚至没有在页面上提及。等一下,我正在为你解答。
    • 谢谢你,我真的很感激你的努力
    【解决方案3】:
    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"));
    

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 2017-09-24
      • 2020-01-28
      • 2015-09-21
      • 2012-02-22
      • 2012-01-17
      • 1970-01-01
      • 2021-02-11
      相关资源
      最近更新 更多