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 tried other possible functions of least astonishment without avail. I just want my bytes as hex!
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 tried other possible functions of least astonishment without avail. I just want my bytes as hex!
The method
binascii.hexlify()
will convertbytes
to abytes
representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a truestr
out then you can.decode("ascii")
the result.I included an snippet that illustrates it.
from the hex string
"0a160a04"
to can come back to thebytes
withbinascii.unhexlify("0a160a04")
which gives backb'\n\x16\n\x04'
Use the
binascii
module:See this answer: Python 3.1.1 string to hex