Convert a string representation of a hex dump to a byte array using Java?
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.
One-liners:
import javax.xml.bind.DatatypeConverter;
public static String toHexString(byte[] array) {
return DatatypeConverter.printHexBinary(array);
}
public static byte[] toByteArray(String s) {
return DatatypeConverter.parseHexBinary(s);
}
Warnings :
eckes
) Fabian
for noting that), but you can just take the source code if your system lacks javax.xml
for some reason. Thanks to @ Bert Regelink
for extracting the source. The Hex class in commons-codec should do that for you.
http://commons.apache.org/codec/
链接地址: http://www.djcxy.com/p/87204.html上一篇: 检查XSLT中的字符串是否为空或为空