代码之家  ›  专栏  ›  技术社区  ›  Aito

将unicode纯文本转换为公共字符串

  •  0
  • Aito  · 技术社区  · 16 年前

    我从外部服务器得到一个unicode字符串,如下所示:

    我必须用java解码。我知道“\u”前缀产生魔力(即“\u0054”->'T'),但我不知道如何将其转换为公共字符串。

    提前谢谢。

    编辑 :谢谢大家。所有答案都有效,但我只能选择一个:(

    再次感谢。

    3 回复  |  直到 16 年前
        1
  •  4
  •   Eyal Schneider    16 年前

    它看起来像UTF-16编码。下面是一个转换它的方法:

    public static String decode(String hexCodes, String encoding) throws UnsupportedEncodingException {
        if (hexCodes.length() % 2 != 0)
            throw new IllegalArgumentException("Illegal input length");
        byte[] bytes = new byte[hexCodes.length() / 2];
        for (int i = 0; i < bytes.length; i++)
            bytes[i] = (byte) Integer.parseInt(hexCodes.substring(2 * i, 2 * i + 2), 16);
        return new String(bytes, encoding);
    }
    
    public static void main(String[] args) throws UnsupportedEncodingException {
        String hexCodes = "005400610020007400650020007400ED0020007400FA0020003F0020003A0029";
        System.out.println(decode(hexCodes, "UTF-16"));
    }
    

    }

    您的示例返回“tate:)”

        2
  •  2
  •   Moritz    16 年前

    Integer.parseInt(s, 16) 获取数值。把它扔给一个 char

    时间:)

        3
  •  1
  •   leonbloy    16 年前

    另一种分析方法:

     public static String mydecode(String hexCode) {
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<hexCode.length();i+=4) 
          sb.append((char)Integer.parseInt(hexCode.substring(i,i+4),16));
        return sb.toString();
     }
    
     public static void main(String[] args)  {
        String hexCodes = "005400610020007400650020007400ED0020007400FA0020003F0020003A0029";
        System.out.println(mydecode(hexCodes));
     }