I have a hex string which looks like:
String hexImage ="0xFFD8FFE000104A46494600010200006400640000FFEC00114475636B79000100040000003C..."
Which I need to convert to an image using Java. I’ve tried converting to a byte array first with org.apache.commons.codec.binary.Hex class. FileOutputStream later dumps this to a file.
char[] charArr= hexImage.toCharArray();
byte[] byteArray = Hex.decodeHex(charArr);
however the parser in the Hex class chokes, with an Decoder exception : Odd number of characters. No matter what method I use to convert to a byte array, it fails. The fileformat is definitely a JPEG.
I’ve tried removing this 0xFF from the string, but the image is corrupt at this point. 0xFF I assume is a the culprit – anyone any ideas on what do I need to do to correct this?
Normally, each byte is represented by 2 hex digits, therefore, if you have an odd number of digits in your HEX string, then something is wrong with it. You can try padding it with 0 in the beginning, such as this:
or at the end, such as this:
However this is not guaranteed to produce a proper image.
On the whole, you should check how you get your hex string. A proper byte sequence should always contain an even number of hex digits.
EDIT: In addition, as Peter Lawrey indicated in his comment, you should check whether the
decodemethod expects0xin front of the string.