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.
The Code presented by Bert Regelink simply does not work. Try the following:
Late to the party, but I have amalgamated the answer above by DaveL into a class with the reverse action - just in case it helps.
And JUnit test class:
For what it's worth, here's another version which supports odd length strings, without resorting to string concatenation.
By far not the cleanest solution. But it works for me and is well formatted:
The output:
Here is a method that actually works (based on several previous semi-correct answers):
The only possible issue that I can see is if the input string is extremely long; calling toCharArray() makes a copy of the string's internal array.
EDIT: Oh, and by the way, bytes are signed in Java, so your input string converts to [0, -96, -65] instead of [0, 160, 191]. But you probably knew that already.
In android ,if you are working with hex, you can try okio.
simple usage:
and result will be