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.
Anderson
  • 3,139
  • 3
  • 33
  • 45

1 Answers1

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?
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • Conclusion: the OP doesn't have the data in `hexString` that they think they have. – Martijn Pieters Apr 27 '16 at 12:20
  • @MartijnPieters `hexString.matches("-?[0-9a-fA-F]+")` return true, refer [this](http://stackoverflow.com/questions/11424540/verify-if-string-is-hexadecimal) – Ankur Singhal Apr 27 '16 at 12:23
  • 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. – Martijn Pieters Apr 27 '16 at 12:25