如何将不可打印的字符或字符串转换为十六进制? [英] How to convert non-printable character or string to hex?
问题描述
我有一个包含下一个十六进制格式的字符串:
5f e8 d0 7b c0 f7 54 07 fb e4 20 f5 b8 10 67 a9
你知道这只是十六进制,我需要从String中获得这个十六进制表示。字符串看起来像:
ED> @@ 2.W.W'KJ%z_ {T g
因此,如何从ED @@ 2.W.W'KJ%z_ {T ghex presentation5f e8 d0 7b c0 f7 54 07 fb e4 20 f5 b8 10 67 a9?这是不可打印的字符,所以我不能使用它:
public static String stringToHex(String arg){
return String.format( %x,新的BigInteger(arg.getBytes()));
}
结果:-10404282104042104042104042104042104042c7eea21040428189104042104042f5。
而且这也给我一些奇怪的东西:
System.out.println(String.format(%h,Integer.toHexString (buff.charAt(0))));
结果:6d1。
此代码有时可用。数据来自套接字(因为我需要以String的形式获取许多答案,并且只有这个Auth Challenge是十六进制的)。
这是正确的解决方案:
public static String toHexString(byte [] bytes){
StringBuilder out = new的StringBuilder();
for(byte b:bytes){
out.append(String.format(%02X,b)+);
}
返回out.toString();
$ / code>
使用 Integer.toHexString()$由于以下原因,c $ c>是错误的:
- 它不会将前导零添加到字节0x01 - 0x0F
- 以2的补码表示形式将字节0x80 - 0xFF打印为负整数
I have String which contain the next hex presentation: "5f e8 d0 7b c0 f7 54 07 fb e4 20 f5 b8 10 67 a9"
You understand that this is just hex and I need to get this hex presentation from String. String looks like: "ED>@@2.W.W'KJ%z_{T g"
So, how to get from "ED>@@2.W.W'KJ%z_{T g" hex presentation "5f e8 d0 7b c0 f7 54 07 fb e4 20 f5 b8 10 67 a9"? This is unprintable characters so I can't use this:
public static String stringToHex(String arg) { return String.format("%x", new BigInteger(arg.getBytes())); }
result: -10404282104042104042104042104042104042c7eea21040428189104042104042f5. And also this returns me something strange:
System.out.println(String.format("%h", Integer.toHexString(buff.charAt(0))));
result: 6d1.
And this code sometimes works. The data comes from socket (as String because I need to get many answers as String and only this Auth Challenge as hex).
解决方案This is the correct solution:
public static String toHexString(byte[] bytes) { StringBuilder out = new StringBuilder(); for (byte b: bytes) { out.append(String.format("%02X", b) + " "); } return out.toString(); }
Solution with
Integer.toHexString()
is wrong for the following reasons:- It doesn't add leading zero to bytes 0x01 - 0x0F
- It prints bytes 0x80 - 0xFF as negative integers in 2's complement representation
这篇关于如何将不可打印的字符或字符串转换为十六进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!