使用Java将十六进制转储的字符串表示形式转换为字节数组? [英] Convert a string representation of a hex dump to a byte array using Java?
问题描述
我正在寻找一种将表示十六进制值的长字符串转换为字节数组的方式。它比发布相同问题的人更好:
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html
但为了保持它的原创性,我会用自己的方式来描述它:假设我有一个字符串00A0BF,我想将其解释为字节[] {0x00,0xA0,0xBf},我应该怎么做?
我是一名Java新手,最终使用BigInteger并注意领先的十六进制零。但我认为这是丑陋的,我确信我缺少一些简单的...
这是我认为的解决方案比以前发布的版本更好:
public static byte [] hexStringToByteArray(String s){
int len = s 。长度();
byte [] data = new byte [len / 2]; (int i = 0; i data [i / 2] =(byte)((Character.digit(s.charAt(i),16 )< 4)
+ Character.digit(s.charAt(i + 1),16));
}
返回数据;
$ / code>
改善原因:
$
-
具有前导零(与BigInteger不同)和负字节值(不像Byte.parseByte)的安全性
不会将字符串转换为 char []
,或者为每个字节创建StringBuilder和String对象。
如果参数不被认为是安全的,可以通过 assert
或异常添加参数检查。 / p>
I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.
I couldn't have phrased it better than the person that posted the same question here:
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html
But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the byte[] {0x00,0xA0,0xBf} what should I do?
I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple...
Here's a solution that I think is better than any posted so far:
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
Reasons why it is an improvement:
Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)
Doesn't convert the String into a
char[]
, or create StringBuilder and String objects for every single byte.
Feel free to add argument checking via assert
or exceptions if the argument is not known to be safe.
这篇关于使用Java将十六进制转储的字符串表示形式转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!