3

可能重复:
使用 Java 将十六进制转储的字符串表示形式转换为字节数组?

For example I get an octet string as follow: 3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d38223f3e3c53 6f6170456e763a456e76656c6f706520786d6c6e733a536f6170456e763d22687474703a2f2f7363 68656d61732e786d6c736f61702e6f72672f736f61702f656e76656c6f70652f223e3c536f617045 6e763a48656164657220786d6c6e733a7773613d22687474703a2f2f7777772e77332e6f72672f32 3030352f30382f61646472657373696e67223e3c7773613a46726f6d3e3c7773613a416464726573 733e43484e594442473c2f7773613a416464726573733e3c2f7773613a46726f6d3e3c7773613a54 6f3e434352433c2f7773613a546f3e3c7773613a416374696f6e3e687474703a2f2f636372632e73 6572766963652e62616e6b636f6d6d2e636f6d2f6162737472616374696f6e2f61746f6d69632f74 6563686e6963616c2e506572736f6e616c4372656469745265706f7274536572762f4661756c743c 2f7773613a416374696f6e3e3c7773613a4d65737361676549443e75726e3a757569643a30303031

而且我知道底层文本是 UTF-8 编码,那么谁能提供一些方法将这些八位字节转换为可读字符串?

4

3 回答 3

5

尝试读取每两个字符,将它们解析为 16 进制整数Integer.parseInt(String,int),将它们添加到字节数组中,并String从结果构造 a :

public static String fromHex(String s) throws UnsupportedEncodingException {
  byte bs[] = new byte[s.length() / 2];
  for (int i=0; i<s.length(); i+=2) {
    bs[i/2] = (byte) Integer.parseInt(s.substring(i, i+2), 16);
  }
  return new String(bs, "UTF8");
}

fromHex("48656c6c6f2c20576f726c6421"); // => "Hello, World!"

您的字符串示例看起来像一个包含 SOAP 消息的 XML 文档。

于 2012-04-26T04:09:08.843 回答
2

看看这里来自 snmp4j的OctetString 。这可能对您有所帮助。

OctetString octetString = new OctetString(java.lang.String);
octetString.toString();
于 2012-04-26T04:02:16.783 回答
1

I think you need to convert it into a byte array first and then building the string, look into Byte class to see if it has a method for getting the byte out of two hex chars, then it would be only a matter of iterating through every two chars and convering them to bytes.

This link may be useful Byte parseByte with radix

于 2012-04-26T03:48:43.060 回答