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

时间:2022-10-12 15:47:21

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

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

I see claims of a bytes.hex method, bytes.decode codecs, and have tried other possible functions of least astonishment without avail. I just want my bytes as hex!

我看到了一个字节的声明。使用十六进制方法,bytes.decode编解码器,并尝试了其他可能的功能,但没有效果。我只是想把我的字节当作十六进制!

6 个解决方案

#1


80  

Use the binascii module:

使用binascii模块:

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

See this answer: Python 3.1.1 string to hex

查看这个答案:Python 3.1.1字符串到十六进制。

#2


138  

Since Python 3.5 this is finally no longer awkward:

从Python 3.5开始,这不再是尴尬的:

>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'

and reverse:

和反向:

>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'

works also with the mutable bytearray type.

也可以使用可变的bytearray类型。

#3


28  

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. In Python 2, you could do:

Python有字节到字节的标准编解码器,可以执行方便的转换,比如可引用的可打印(适合于7bits ascii)、base64(适合于字母数字)、十六进制转义、gzip和bz2压缩。在python2里,你可以这样做:

b'foo'.encode('hex')

In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):

在python3中,string .encode / bytes.decode是严格的字节<->str转换。相反,你可以这样做,它可以在Python 2和Python 3之间进行(s/编码/解码/g的逆):

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

Starting with Python 3.4, there is a less awkward option:

从Python 3.4开始,有一个不那么尴尬的选项:

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

These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.

这些misc编解码器也可以在自己的模块中访问(base64、zlib、bz2、uu、quopri、binascii);这个API不那么一致,但是对于压缩编解码器,它提供了更多的控制。

#4


7  

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

works in Python 3.3 (so "hex_codec" instead of "hex").

在Python 3.3中工作(so“hex_codec”而不是“hex”)。

#5


3  

The method binascii.hexlify() will convert bytes to a bytes representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a true str out then you can .decode("ascii") the result.

方法binascii.hexlify()将字节转换为表示ascii十六进制字符串的字节。这意味着输入中的每个字节将被转换为两个ascii字符。如果你想要一个真正的str,那么你可以。decode(“ascii”)的结果。

I included an snippet that illustrates it.

我包括了一个说明它的代码片段。

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

from the hex string "0a160a04" to can come back to the bytes with binascii.unhexlify("0a160a04") which gives back b'\n\x16\n\x04'

从hex字符串“0a160a04”可以返回到与binascii.unhexlify(“0a160a04”)的字节,它返回b'\n\x16\n\x04'

#6


0  

If you want to convert b'\x61' to 97 or '0x61', you can try this:

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

Reference:https://docs.python.org/3.5/library/struct.html

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

#1


80  

Use the binascii module:

使用binascii模块:

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

See this answer: Python 3.1.1 string to hex

查看这个答案:Python 3.1.1字符串到十六进制。

#2


138  

Since Python 3.5 this is finally no longer awkward:

从Python 3.5开始,这不再是尴尬的:

>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'

and reverse:

和反向:

>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'

works also with the mutable bytearray type.

也可以使用可变的bytearray类型。

#3


28  

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. In Python 2, you could do:

Python有字节到字节的标准编解码器,可以执行方便的转换,比如可引用的可打印(适合于7bits ascii)、base64(适合于字母数字)、十六进制转义、gzip和bz2压缩。在python2里,你可以这样做:

b'foo'.encode('hex')

In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):

在python3中,string .encode / bytes.decode是严格的字节<->str转换。相反,你可以这样做,它可以在Python 2和Python 3之间进行(s/编码/解码/g的逆):

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

Starting with Python 3.4, there is a less awkward option:

从Python 3.4开始,有一个不那么尴尬的选项:

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

These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.

这些misc编解码器也可以在自己的模块中访问(base64、zlib、bz2、uu、quopri、binascii);这个API不那么一致,但是对于压缩编解码器,它提供了更多的控制。

#4


7  

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

works in Python 3.3 (so "hex_codec" instead of "hex").

在Python 3.3中工作(so“hex_codec”而不是“hex”)。

#5


3  

The method binascii.hexlify() will convert bytes to a bytes representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a true str out then you can .decode("ascii") the result.

方法binascii.hexlify()将字节转换为表示ascii十六进制字符串的字节。这意味着输入中的每个字节将被转换为两个ascii字符。如果你想要一个真正的str,那么你可以。decode(“ascii”)的结果。

I included an snippet that illustrates it.

我包括了一个说明它的代码片段。

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

from the hex string "0a160a04" to can come back to the bytes with binascii.unhexlify("0a160a04") which gives back b'\n\x16\n\x04'

从hex字符串“0a160a04”可以返回到与binascii.unhexlify(“0a160a04”)的字节,它返回b'\n\x16\n\x04'

#6


0  

If you want to convert b'\x61' to 97 or '0x61', you can try this:

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

Reference:https://docs.python.org/3.5/library/struct.html

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