2016-04-27 234 views
0

在Python,我可以十六進制轉換爲這樣的事情..JAVA轉換十六進制字符串

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. 
+0

錯誤信息是非常明顯的。 – Hackerdarshi

+0

您在那裏的十六進制數據是*不是UTF-8數據*。 Python代碼從不嘗試將字節解釋爲文本編碼,您所擁有的只是字節。 –

+0

@Hackerdarshi所以如何在Java中做同樣的事情? – Anderson

回答

2

這對我的作品

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? 
+0

結論:OP沒有'hexString'他們認爲他們有數據。 –

+0

@MartijnPieters'hexString.matches(「 - ?[0-9a-fA-F] +」)'返回true,請參考[this](http://stackoverflow.com/questions/11424540/verify-if-string-是 - 十六進制) –

+0

這與OP的輸入中沒有偶數個十六進制數字有什麼關係?而在開始時允許'-'只會讓事情變得更糟,而不是更好。 –

相關問題