JAVA转换十六进制字符串

时间:2016-04-27 12:10:25

标签: java python hex decode codec

在Python中,我可以将hex转换为类似的东西..

s = "6025ce2069c61b15d8314f7cdd76b850dcd339547335d0e4a1e0b9915b0230cd"

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

我的问题是如何用Java做同样的事情?

我是这样用Java做的,但它引发了异常。

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

错误消息是这样的。

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

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

我删除了UTF-8,但我仍然得到同样的例外..请帮忙!

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

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

1 个答案:

答案 0 :(得分:3)

这对我有用

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"));
    }

<强>输出

`%? i??1O|?v?P??9Ts5???[0?