簡體   English   中英

如何從十六進制編碼的字符串解碼為UTF-8字符串

[英]How to decode to UTF-8 String from Hex encoded string

我得到了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嗎?

這應該足以讓您入門。 我將保留實現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;
}
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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM