Anderson
Anderson

Reputation: 3247

JAVA Converting Hexadecimal String

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.

Upvotes: 1

Views: 2544

Answers (1)

Ankur Singhal
Ankur Singhal

Reputation: 26077

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?

Upvotes: 3

Related Questions