簡體   English   中英

在 Python 3 中將字節轉換為十六進制字符串的正確方法是什么?

[英]What's the correct way to convert bytes to a hex string in Python 3?

在 Python 3 中將字節轉換為十六進制字符串的正確方法是什么?

我看到了有關bytes.hex方法、 bytes.decode編解碼器的聲明,並嘗試了其他可能的功能,但無濟於事。 我只希望我的字節為十六進制!

由於 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

使用binascii模塊:

>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'

看到這個答案: Python 3.1.1 字符串到十六進制

Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. 在 Python 2 中,您可以執行以下操作:

b'foo'.encode('hex')

在 Python 3 中, str.encode / bytes.decode嚴格用於 bytes<->str 轉換。 相反,您可以這樣做,它適用於 Python 2 和 Python 3 ( s/encode/decode/g為反向):

import codecs
codecs.getencoder('hex')(b'foo')[0]

從 Python 3.4 開始,有一個不太尷尬的選項:

codecs.encode(b'foo', 'hex')

這些雜項編解碼器也可以在它們自己的模塊中訪問(base64、zlib、bz2、uu、quopri、binascii); API 不太一致,但對於壓縮編解碼器,它提供了更多控制。

python 3.8 中的新功能,您可以將分隔符參數傳遞給hex function,如本例所示

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

https://docs.python.org/3/library/stdtypes.html#bytes.hex

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'

import codecs
codecs.getencoder('hex_codec')(b'foo')[0]

適用於 Python 3.3(所以“hex_codec”而不是“hex”)。

OK, the following answer is slightly beyond-scope if you only care about Python 3, but this question is the first Google hit even if you don't specify the Python version, so here's a way that works on both Python 2 and Python 3 .

我還將這個問題解釋為關於將字節轉換為str類型:即 Python 2 上的 bytes-y 和 Python 3 上的 Unicode-y。

鑒於此,我所知道的最佳方法是:

import six

bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))

以下斷言對於 Python 2 或 Python 3 都是正確的,假設您尚未在 ZA7F5F35426B927411FC9231B563821 中激活unicode_literals未來:

assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'

(或者您可以使用''.join()省略字節之間的空格等)

可以使用格式說明符%x02 x02 表示格式,output 是十六進制值。 例如:

>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
...     res += "%02x" % b
... 
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736

如果你想將 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'

參考: https://docs.python.org/3.5/library/struct.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM