简体   繁体   中英

How to convert this hex string to unicode in java?

I get below result from a web service:

 "\\x52\\x50\\x1F\\x1F\\x44\\x46\\x57\\x47"

I need to get the strings in unicode characters, which i think would be:

"\u0052\u0050\u001F\u001F\u0044\u0046\u0057\u0047"

ie "RPDFWG"

I cannot use replace("\\\\x", "\\u00\u0026quot;); because it says "\\u00\u0026quot; is not a valid unicode

This code works for me:

try {
  String orig = "\\x52\\x50\\x1F\\x1F\\x44\\x46\\x57\\x47";
  byte[] bytes = new byte[orig.length() / 4];

  for (int i = 0; i < orig.length(); i += 4) {
    bytes[i / 4] = (byte) Integer.parseInt(orig.substring(i + 2, i + 4), 16);
  }

  System.out.println(new String(bytes, "UTF-8"));
}
catch (Exception e) {
  e.printStackTrace();
}

You might want to change the encoding to ISO-8859-1 , or just plain ASCII -- I can't tell from your example what encoding is relevant here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM