What\'s the correct way to convert bytes to a hex string in Python 3?
I see claims of a bytes.hex
method, bytes.decode
codecs, and have tri
If you want to convert b'\x61' to 97 or '0x61', you can try this:
[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
Use the binascii
module:
>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'
See this answer: Python 3.1.1 string to hex
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.
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'