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.
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.
I think will do it for you. I cobbled it together from a similar function that returned the data as a string:
Here's a solution that I think is better than any posted so far:
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.No library dependencies that may not be available
Feel free to add argument checking via
assert
or exceptions if the argument is not known to be safe.EDIT: as pointed out by @mmyers, this method doesn't work on input that contains substrings corresponding to bytes with the high bit set ("80" - "FF"). The explanation is at Bug ID: 6259307 Byte.parseByte not working as advertised in the SDK Documentation.
I found Kernel Panic to have the solution most useful to me, but ran into problems if the hex string was an odd number. solved it this way:
I am adding a number of hex numbers to an array, so i pass the reference to the array I am using, and the int I need converted and returning the relative position of the next hex number. So the final byte array has [0] number of hex pairs, [1...] hex pairs, then the number of pairs...
The
HexBinaryAdapter
provides the ability to marshal and unmarshal betweenString
andbyte[]
.That's just an example I typed in...I actually just use it as is and don't need to make a separate method for using it.
Actually, I think the BigInteger is solution is very nice:
Edit: Not safe for leading zeros, as noted by the poster.