在Python 3中将字节转换为十六进制字符串的正确方法是什么?

问题描述 投票:192回答:8

在Python 3中将字节转换为十六进制字符串的正确方法是什么?

我看到了bytes.hex方法,bytes.decode编解码器的主张,并尝试了other最小惊讶的可能功能,但无济于事。我只希望我的字节为十六进制!

python python-3.x hex
8个回答
322
投票

从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


94
投票

使用binascii模块:

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

查看此答案:Python 3.1.1 string to hex


38
投票

Python具有逐字节standard codecs,可以执行方便的转换,例如带引号的可打印(适合7位ascii),base64(适合字母数字),十六进制转义,gzip和bz2压缩。在Python 2中,您可以执行以下操作:

b'foo'.encode('hex')

在Python 3中,str.encode / bytes.decode严格用于bytesstr转换。相反,您可以执行此操作,该操作适用于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的一致性较差,但对于压缩编解码器,它提供了更多控制权。


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

在Python 3.3中有效(因此是“ hex_codec”而不是“ hex”)。


6
投票

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"可以返回到bytes并返回binascii.unhexlify("0a160a04")b'\n\x16\n\x04'


3
投票

[好吧,如果您仅关心Python 3,以下答案会稍微超出范围,但是即使您未指定Python版本,此问题也是Google的第一招,因此这是在两种Python 2上均可使用的方法< [和 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都是正确的,假设您尚未在Python 2中激活unicode_literals future:

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

(或者您可以使用''.join()省略字节之间的空格,等等。]

2
投票
可以使用格式说明符%x02格式化并输出一个十六进制值。例如:

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


-1
投票
如果要将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
© www.soinside.com 2019 - 2024. All rights reserved.