Mat*_*ner 194 python hex python-3.x
在Python 3中将字节转换为十六进制字符串的正确方法是什么?
我看到了一种bytes.hex方法,bytes.decode编解码器的主张,并尝试了其他可能的功能,最不惊讶,但没有用.我只想把我的字节作为十六进制!
小智 324
从Python 3.5开始,这终于不再尴尬了:
>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'
Run Code Online (Sandbox Code Playgroud)
并反转:
>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'
Run Code Online (Sandbox Code Playgroud)
也适用于可变bytearray类型.
Mu *_*ind 94
使用binascii模块:
>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'
Run Code Online (Sandbox Code Playgroud)
看到这个答案: Python 3.1.1字符串到十六进制
Gab*_*iel 38
Python具有字节到字节的标准编解码器,可执行方便的转换,如quoted-printable(适合7位ascii),base64(适合字母数字),hex转义,gzip和bz2压缩.在Python 2中,您可以:
b'foo'.encode('hex')
Run Code Online (Sandbox Code Playgroud)
在Python 3中,str.encode/ bytes.decode严格用于字节< - > str转换.相反,你可以这样做,它适用于Python 2和Python 3(s/encode/decode/g用于反向):
import codecs
codecs.getencoder('hex')(b'foo')[0]
Run Code Online (Sandbox Code Playgroud)
从Python 3.4开始,有一个不太尴尬的选择:
codecs.encode(b'foo', 'hex')
Run Code Online (Sandbox Code Playgroud)
这些misc编解码器也可以在他们自己的模块中访问(base64,zlib,bz2,uu,quopri,binascii); API不太一致,但对于压缩编解码器,它提供了更多控制.
python 3.8中的新功能,您可以将分隔符参数传递给hex函数,如本例所示
>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'
Run Code Online (Sandbox Code Playgroud)
https://docs.python.org/3/library/stdtypes.html#bytes.hex
小智 7
import codecs
codecs.getencoder('hex_codec')(b'foo')[0]
Run Code Online (Sandbox Code Playgroud)
适用于Python 3.3(所以"hex_codec"而不是"hex").
该方法binascii.hexlify()将转换bytes为bytes表示ascii十六进制字符串的a.这意味着输入中的每个字节都将转换为两个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
Run Code Online (Sandbox Code Playgroud)
从十六进制字符串"0a160a04"到可以回来了bytes与binascii.unhexlify("0a160a04")该还给b'\n\x16\n\x04'
小智 6
可以使用格式说明符%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
Run Code Online (Sandbox Code Playgroud)