Whats the correct way to convert bytes to a hex string in Python 3?
Whats the correct way to convert bytes to a hex string in Python 3?
Since Python 3.5 this is finally no longer awkward:
>>> bxdexadxbexef.hex()
deadbeef
and reverse:
>>> bytes.fromhex(deadbeef)
bxdexadxbexef
works also with the mutable bytearray
type.
Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex
Use the binascii
module:
>>> import binascii
>>> binascii.hexlify(foo.encode(utf8))
b666f6f
>>> binascii.unhexlify(_).decode(utf8)
foo
See this answer:
Python 3.1.1 string to hex
Whats the correct way to convert bytes to a hex string in Python 3?
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:
bfoo.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):
import codecs
codecs.getencoder(hex)(bfoo)[0]
Starting with Python 3.4, there is a less awkward option:
codecs.encode(bfoo, 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.