![](/img/trans.png)
[英]In Java I need to convert an XML Document to a string, with non-printable characters in data as hex
[英]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 g”十六进制表示形式“ 5f 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", new BigInteger(arg.getBytes()));
}
结果:-10404282104042104042104042104042104042c7eea21040428189104042104042f5。
而且这还给我带来了一些奇怪的东西:
System.out.println(String.format("%h", Integer.toHexString(buff.charAt(0))));
结果:6d1。
并且此代码有时有效。 数据来自套接字(作为字符串,因为我需要以字符串形式获得许多答案,而只有此身份验证挑战为十六进制)。
这是正确的解决方案:
public static String toHexString(byte[] bytes) {
StringBuilder out = new StringBuilder();
for (byte b: bytes) {
out.append(String.format("%02X", b) + " ");
}
return out.toString();
}
由于以下原因,使用Integer.toHexString()
解决方案是错误的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.