【问题标题】:JAVA Converting Hexadecimal StringJAVA转换十六进制字符串
【发布时间】:2016-04-27 12:10:24
【问题描述】:

在 Python 中,我可以将十六进制转换为类似的东西..

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.

【问题讨论】:

  • 错误信息已经够清楚了。
  • 您拥有的十六进制数据不是 UTF-8 数据。 Python 代码从不尝试将字节解释为文本编码,您所拥有的只是字节。
  • @Hackerdarshi 那么如何在 Java 中做同样的事情呢?
  • 您的 combined 变量 - 它包含什么?

标签: java python hex decode codec


【解决方案1】:

这对我有用

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?

【讨论】:

  • 结论:OP 在hexString 中没有他们认为拥有的数据。
  • @MartijnPieters hexString.matches("-?[0-9a-fA-F]+") 返回真,参考this
  • 这与 OP 在其输入中没有偶数个十六进制数字这一事实有什么关系?在开始时允许- 只会让事情变得更糟,而不是更好。
猜你喜欢
  • 1970-01-01
  • 2018-01-31
  • 2016-07-25
  • 2015-06-21
  • 2014-10-24
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 2014-03-10
相关资源
最近更新 更多