为了记录目的,我们将日志转换为字节数组,然后转换为十六进制字符串.我想在Java String中取回它,但我无法这样做.
日志文件中的十六进制字符串看起来像
fd00000aa8660b5b010006acdc0100000101000100010000
Run Code Online (Sandbox Code Playgroud)
我怎么解码这个?
Rei*_*eus 57
Hex在Apache Commons中使用:
String hexString = "fd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println(new String(bytes, "UTF-8"));
Run Code Online (Sandbox Code Playgroud)
tel*_*bog 28
byte[] bytes = DatatypeConverter.parseHexBinary(hexString);
String result= new String(bytes, encoding);
Run Code Online (Sandbox Code Playgroud)
你可以去从String (hex)到byte array到String as UTF-8(?).确保您的十六进制字符串没有前导空格和内容.
public static byte[] hexStringToByteArray(String hex) {
int l = hex.length();
byte[] data = new byte[l/2];
for (int i = 0; i < l; i += 2) {
data[i/2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i+1), 16));
}
return data;
}
Run Code Online (Sandbox Code Playgroud)
用法:
String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);
Run Code Online (Sandbox Code Playgroud)
首先读取数据,然后将其转换为字节数组:
byte b = Byte.parseByte(str, 16);
Run Code Online (Sandbox Code Playgroud)
然后使用String构造函数:
new String(byte[] bytes)
Run Code Online (Sandbox Code Playgroud)
或者如果字符集不是系统默认值,则:
new String(byte[] bytes, String charsetName)
Run Code Online (Sandbox Code Playgroud)
如果使用 JDK17 或更高版本,还有另一种方法可以做到这一点,请参阅新的 HexFormat类,它具有用于转换byte[]<=> 十六进制的有用方法String:
String hexStr ="5468697320697320616e206578616d706c6520737472696e67";
byte[] bytes = HexFormat.of().parseHex(hexStr);
String str = new String(bytes, StandardCharsets.UTF_8 /* or Charset.forName("whateverencoding")*/);
Run Code Online (Sandbox Code Playgroud)
您当然需要知道十六进制表示的确切字符编码才能生成正确的String值。
小智 5
尝试以下代码:
public static byte[] decode(String hex){
String[] list=hex.split("(?<=\\G.{2})");
ByteBuffer buffer= ByteBuffer.allocate(list.length);
System.out.println(list.length);
for(String str: list)
buffer.put(Byte.parseByte(str,16));
return buffer.array();
}
Run Code Online (Sandbox Code Playgroud)
要转换为String,只需使用解码方法返回的byte []创建一个新的String。
将十六进制字符串转换为 java 字符串的另一种方法:
public static String unHex(String arg) {
String str = "";
for(int i=0;i<arg.length();i+=2)
{
String s = arg.substring(i, (i + 2));
int decimal = Integer.parseInt(s, 16);
str = str + (char) decimal;
}
return str;
}
Run Code Online (Sandbox Code Playgroud)