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.
For those of you interested in the actual code behind the One-liners from FractalizeR (I needed that since javax.xml.bind is not available for Android (by default)), this comes from com.sun.xml.internal.bind.DatatypeConverterImpl.java :
If you have a preference for Java 8 streams as your coding style then this can be achieved using just JDK primitives.
The
, 0, s2.size()
parameters in the collector concatenate function can be omitted if you don't mind catchingIOException
.Based on the op voted solution, the following should be a bit more efficient:
Because: the initial conversion to a char array spares the length checks in charAt
For Me this was the solution, HEX="FF01" then split to FF(255) and 01(01)
I've always used a method like
this method splits on space delimited hex values but it wouldn't be hard to make it split the string on any other criteria such as into groupings of two characters.