如何从十六进制编码的字符串解码为UTF-8字符串

时间:2014-04-22 01:47:43

标签: java javascript

我得到HTML Javascript字符串,例如:

htmlString = "https\x3a\x2f\x2ftest.com"

但我想将其解码如下:

str = "https://test.com"

这意味着,我想要一个Util API,如:

 public static String decodeHex(String htmlString){
   // do decode and converter here 
 }

 public static void main(String ...args){
       String htmlString = "https\x3a\x2f\x2ftest.com";
       String str = decodeHex(htmlString);
       // str should be "https://test.com"
 }

有谁知道如何实现这个API - decodeHex?

2 个答案:

答案 0 :(得分:1)

这应该足以让你入门。我将实施hexDecode并将错误输入作为练习进行整理。

public String decode(String encoded) {
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < encoded.length(); i++) {
    if (encoded.charAt(i) == '\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
      sb.append(hexDecode(encoded.substring(i + 2, i + 4)));
      i += 3;
    } else {
      sb.append(encoded.charAt(i));
    }
  }
  return sb.toString;
}

答案 1 :(得分:0)

public String decode(String encoded) throws DecoderException {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < encoded.length(); i++) {
        if (encoded.charAt(i) == '\\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
          sb.append(new String(Hex.decodeHex(encoded.substring(i + 2, i + 4).toCharArray()),StandardCharsets.UTF_8));
          i += 3;
        } else {
          sb.append(encoded.charAt(i));
        }
      }
      return sb.toString();
    }