1

In Python, I can convert hex to something like this..

s = "6025ce2069c61b15d8314f7cdd76b850dcd339547335d0e4a1e0b9915b0230cd"

s.decode('hex')
'`%\xce i\xc6\x1b\x15\xd81O|\xddv\xb8P\xdc\xd39Ts5\xd0\xe4\xa1\xe0\xb9\x91[\x020\xcd'

My question is how to do the same thing in Java?

I did this in Java like this but it raises an exception.

new String(Hex.decodeHex(str.toCharArray()), "UTF-8"

The error messege is like this.

Exception in thread "main" org.apache.commons.codec.DecoderException: Odd number of characters.

========================================================

I removed UTF-8 but I am still getting the same exception.. please help!

new String(Hex.decodeHex(combined.toCharArray()))

Exception in thread "main" org.apache.commons.codec.DecoderException: Odd number of characters.
5
  • The error message is clear enough. Commented Apr 27, 2016 at 12:11
  • The hex data you have there is not UTF-8 data. The Python code never tries to interpret the bytes as a text encoding, all you have is bytes still. Commented Apr 27, 2016 at 12:11
  • @Hackerdarshi so how to do the same thing in Java? Commented Apr 27, 2016 at 12:12
  • Your combined variable - what does it contain? Commented Apr 27, 2016 at 12:16
  • Please checkout the answer in this question: stackoverflow.com/questions/10143135/hex-string-to-image Commented Apr 27, 2016 at 12:19

1 Answer 1

3

This works for me

public static void main(String[] args) throws ParseException, DecoderException, UnsupportedEncodingException {
        String hexString = "6025ce2069c61b15d8314f7cdd76b850dcd339547335d0e4a1e0b9915b0230cd";
        byte[] bytes = Hex.decodeHex(hexString.toCharArray());
        System.out.println(new String(bytes , "UTF-8"));
    }

Output

`%? i??1O|?v?P??9Ts5???[0?
Sign up to request clarification or add additional context in comments.

3 Comments

Conclusion: the OP doesn't have the data in hexString that they think they have.
@MartijnPieters hexString.matches("-?[0-9a-fA-F]+") return true, refer this
What does that have to do with the fact that the OP does not have an even number of hex digits in their input? And allowing a - at the start will only make matters worse, not better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.