Convert hexadecimal HEX to UTF-8 in bytecode in java

Got a problem today.

Due to improper handling of product version management and compatibility, an error occurs when connecting with other products during product upgrade. Since it is a product from N years ago, it is no longer possible to view the original configuration. Had to capture the packet data. There was a small episode, although the data was captured through Tcpdump, some of the key items were in Chinese, which was opened with wireshark to display a series of dots. This is a garbled code (later found out, in fact, as long as you save as the following, it can be displayed normally)!

I was thinking of finding an online transcoding tool, but I couldn't convert it after trying a few. I can only try to use code to deal with it, start looking for information, and find that there is actually more than one way to deal with it.

First open it with UE, you can see the UTF-8 hexadecimal data.

[Method 1] Use shell

[Method 2] Write code to achieve

public class Test {

 public static String str2Hex(String str) throws UnsupportedEncodingException {
  String hexRaw = String.format("%x", new BigInteger(1, str.getBytes("UTF-8")));
  char[] hexRawArr = hexRaw.toCharArray();
  StringBuilder hexFmtStr = new StringBuilder();
  final String SEP = "\\x";
  for (int i = 0; i < hexRawArr.length; i++) {
   hexFmtStr.append(SEP).append(hexRawArr[i]).append(hexRawArr[++i]);
  }
  return hexFmtStr.toString();
 }

 public static String hex2Str(String str) throws UnsupportedEncodingException {
  String strArr[] = str.split("\\\\"); // 分割拿到形如 xE9 的16进制数据
  byte[] byteArr = new byte[strArr.length - 1];
  for (int i = 1; i < strArr.length; i++) {
   Integer hexInt = Integer.decode("0" + strArr[i]);
   byteArr[i - 1] = hexInt.byteValue();
  }

  return new String(byteArr, "UTF-8");
 }

 public static void main(String[] args) throws UnsupportedEncodingException {

  System.out.println(str2Hex("中国1a23"));
  System.out.println(hex2Str(str2Hex("中国1a23")));
  System.out.println(hex2Str("\\xE9\\xBB\\x84\\xE8\\x8A\\xB1\\xE6\\xA2\\xA8\\xE5\\xAE\\xB6\\xE5\\x85\\xB7\\xE8\\xBD\\xAC\\xE8\\xAE\\xA9"));
 }

}

result:


\xe4\xb8\xad\xe5\x9b\xbd\x31\x61\x32\
x33China 1a23
Huanghuali Furniture For Sale

 
Let's take a look at how the unicode form is converted in java:

 

String string = "中国\u6211\u7231\u5317\u4EAC";
byte[] utf8 = string.getBytes("UTF-8");
string = new String(utf8, "UTF-8");
System.out.println(string);

 

 

 

 

 

Link

https://my.oschina.net/leejun2005/blog/106791

http://www.cnblogs.com/developerY/p/3575271.html

http://stackoverflow.com/questions/28086916/encode-decode-hex-to-utf-8-string

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326822021&siteId=291194637