bytearray.fromhex不會轉換我試圖轉換文本文件數據(它是以ANSI編碼)十六進制值使用當Alphabates(A,B,C,D,E,F)出現在號碼
line = bytearray.fromhex(x)
但它顯示下面的錯誤。
line = bytearray.fromhex(x) ValueError: non-hexadecimal number found in fromhex() arg at position 5
如何才能實現正確的轉換?請給我一個解決方案。
bytearray.fromhex不會轉換我試圖轉換文本文件數據(它是以ANSI編碼)十六進制值使用當Alphabates(A,B,C,D,E,F)出現在號碼
line = bytearray.fromhex(x)
但它顯示下面的錯誤。
line = bytearray.fromhex(x) ValueError: non-hexadecimal number found in fromhex() arg at position 5
如何才能實現正確的轉換?請給我一個解決方案。
您必須先將文本編碼爲十六進制格式。你可以使用encode
這個功能。
The method encode() returns an encoded version of the string. Default encoding is the current default string encoding. The errors may be given to set a different error handling scheme.
試試這個:
line = bytearray.fromhex(x.encode("hex"))
編輯:
對於Python 3.4和更高版本,你需要通過編解碼器模塊和hex_codec編解碼器去:
line = bytearray.fromhex(codecs.encode(x, 'hex_codec'))
line = bytearray.fromhex(x.encode(「hex」)) LookupError:'hex'不是文本編碼;使用codecs.encode()來處理任意的編解碼器,這裏「hex」是什麼? –
@TarangJain請參閱我爲Python 3.4及更高版本編輯的答案。 –
@TarangJain您是否可以使用上述解決方案解決問題? –
編碼='ANSI';所以它不會超出127(7F),我怎樣才能以十六進制轉換7F以上的值。 –