在Java中,如何将十六进制字符串转换为byte[]?
我正在 Java 中使用以下函数将加密字符串转换为十六进制格式:
public static String toHex(byte [] buf) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10) {
strbuf.append("0");
}
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
现在我想将该十六进制字符串转换回字节数组。我怎样才能做到这一点?
例如,
(1) Plain Text = 123
(2) Encrypted Text = «h>kq*«¬Mí“~èåZ \}?
(3) Encrypted Text in Hex = f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e
我可以从 (2)
转到 (3)
,但是如何从 (3)
返回到 (2) ?
I am using the below function in Java to convert an encrypted String into hex format:
public static String toHex(byte [] buf) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10) {
strbuf.append("0");
}
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
Now I want to convert that hex string back into a byte array. How can I do that?
For example,
(1) Plain Text = 123
(2) Encrypted Text = «h>kq*«¬Mí“~èåZ \}?
(3) Encrypted Text in Hex = f263575e7b00a977a8e9a37e08b9c215feb9bfb2f992b2b8f11e
I can go from (2)
to (3)
, but how do I go from (3)
back to (2)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
接受的答案不考虑可能导致问题的前导零
这个问题回答了它。取决于您是想看看它是如何完成的还是只是使用 java 内置方法。以下是从此和这分别回答了提到的SO问题。
选项 1:Util 方法
选项 2:单行内置
The accepted answer does not consider leading zeros which may cause problems
This question answers it. Depending on whether you want to see how its done or just use a java built-in method. Here are the solutions copied from this and this answers respectively from the SO question mentioned.
Option 1: Util method
Option 2: One-liner build-in
我发现 DatatypeConverter.parseHexBinary 的成本比以下成本更高(两倍):
I found that the DatatypeConverter.parseHexBinary is more costly (two times) than: