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!
To convert a byte to hexadecimal equivalent, use the toHexString() method in Java. Firstly, let us take a byte value. byte val1 = (byte)90; Before using the method, let us do some more manipulations.
To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.
Since Python 3.5 this is finally no longer awkward:
>>> b'\xde\xad\xbe\xef'.hex() 'deadbeef'
and reverse:
>>> bytes.fromhex('deadbeef') b'\xde\xad\xbe\xef'
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')) b'666f6f' >>> binascii.unhexlify(_).decode('utf8') 'foo'
See this answer: Python 3.1.1 string to hex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With