在Python 3中將字節轉換爲十六進制字符串的正確方法是什麼?在Python 3中將字節轉換爲十六進制字符串的正確方法是什麼?
我看到一個bytes.hex
方法的索賠,bytes.decode
編解碼器,並試圖other可能的功能最小的驚訝,無濟於事。我只是想要我的字節爲十六進制!
在Python 3中將字節轉換爲十六進制字符串的正確方法是什麼?在Python 3中將字節轉換爲十六進制字符串的正確方法是什麼?
我看到一個bytes.hex
方法的索賠,bytes.decode
編解碼器,並試圖other可能的功能最小的驚訝,無濟於事。我只是想要我的字節爲十六進制!
使用binascii
模塊:
>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'
看到這個答案: Python 3.1.1 string to hex
這很好。令人難以置信的是,你可以使用bytes.fromhex(hex_str)將hex轉換爲字節,但不能使用bytes.tohex()將字節轉換爲十六進制 - 這是什麼理由? – nagylzs
我猜字節和十六進制之間的關係不是任何一個的屬性(它不回答爲什麼fromhex在那裏)。看起來這不僅僅是一個疏忽,而是一個爭論的話題:http://bugs.python.org/issue3532#msg70950。 問:使用bytes對象的tohex方法執行此任務會有什麼不好嗎? A:國際海事組織,是的,它會。它使代碼複雜化,並將注意力從適當的數據轉換方法(即函數 - 而不是方法)上吸引。 –
這是否真的回答了這個問題?它不會返回一個十六進制的'str',而是一個'bytes'。我知道OP似乎對答案似乎很滿意,但將這個答案擴展爲包含'.decode(「ascii」)'也可以將它轉換爲「字符串」更好。 – ecerulm
Python有個字節到字節standard codecs執行方便的轉換像引用可打印(適合7位ASCII)的base64 (適合字母數字),十六進制轉義,gzip和bz2壓縮。在Python 2,你可以這樣做:
b'foo'.encode('hex')
在Python 3,str.encode
/bytes.decode
嚴格的字節< - >海峽轉換。相反,你可以做到這一點,其中不同的Python 2和Python 3作品(S /編碼/解碼/ G的倒數):
import codecs
codecs.getencoder('hex')(b'foo')[0]
與Python 3.4開始,有一個不太尷尬的選擇:
codecs.encode(b'foo', 'hex')
這些misc編解碼器也可以在它們自己的模塊(base64,zlib,bz2,uu,quopri,binascii)中訪問; API不太一致,但對於壓縮編解碼器,它提供了更多的控制。
使用python 3.3:'LookupError:unknown encoding:hex' –
@JanusTroelsen:嘗試['hex_codec'](http://stackoverflow.com/a/22465079/4279)。或者直接使用'binascii.hexlify(b'foo')' – jfs
import codecs
codecs.getencoder('hex_codec')(b'foo')[0]
在Python 3.3中工作(so「hex_codec」,而不是「hex」)。
也許有趣的是,在Python 3.4中,「hex」或「hex_codec」可以正常工作。 –
方法binascii.hexlify()
將bytes
轉換爲表示ascii十六進制字符串的bytes
。這意味着輸入中的每個字節都將轉換爲兩個ASCII字符。如果你想真的str
出來,那麼你可以.decode("ascii")
的結果。
我收錄了一個說明它的片段。
import binascii
with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
in_bytes = f.read()
print(in_bytes) # b'\n\x16\n\x04'
hex_bytes = binascii.hexlify(in_bytes)
print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
hex_str = hex_bytes.decode("ascii")
print(hex_str) # 0a160a04
從十六進制字符串"0a160a04"
到可以binascii.unhexlify("0a160a04")
這回來到bytes
還給b'\n\x16\n\x04'
因爲Python 3.5,這是終於不再尷尬:
>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'
和反向:
>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'
也適用於可變的bytearray
類型。
參考:https://docs.python.org/3/library/stdtypes.html#bytes.hex – minexew
如果要轉換B'\ x61的97或 '0x61',你可以試試這個:
[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'
「無果」?你得到了哪些具體的**問題或錯誤?請顯示代碼和錯誤。 –
可能的重複http://stackoverflow.com/questions/2340319/python-3-1-1-string-to-hex –