Home > Article > Backend Development > How to Easily Convert Bytes to Hex and Back in Python 3?
Hex Conversion of Bytes in Python 3: A Simplified Approach
There's often confusion around converting bytes to hexadecimal strings in Python 3. You may have encountered claims about a non-existent bytes.hex method or attempted various functions with no luck. This article aims to provide a straightforward solution to this conversion challenge.
From Bytes to Hex
In Python 3.5 and later, the process has become significantly easier with the introduction of the hex method:
>>> b'\xde\xad\xbe\xef'.hex() 'deadbeef'
This method conveniently generates a hexadecimal representation of the bytes in lower case.
From Hex to Bytes
To convert a hexadecimal string back to bytes, use the bytes.fromhex function:
>>> bytes.fromhex('deadbeef') b'\xde\xad\xbe\xef'
This function converts the hexadecimal string into the corresponding bytes, restoring its original byte form.
Note:
This method also works with the mutable bytearray type.
References:
For further details and examples, refer to the official Python documentation: https://docs.python.org/3/library/stdtypes.html#bytes.hex
The above is the detailed content of How to Easily Convert Bytes to Hex and Back in Python 3?. For more information, please follow other related articles on the PHP Chinese website!