Home >Backend Development >Python Tutorial >How to Convert Bytes to Hex Strings and Vice Versa in Python 3?
Bytes to Hex String Conversion in Python 3
Converting bytes to a hex string in Python 3 has long been a subject of confusion. This question seeks a clear and straightforward solution.
The original bytes.hex method is no longer accessible in Python versions prior to 3.5. Instead, Python 3.5 introduces a dedicated hex() method for byte sequences:
<br>In [1]: b'xdexadxbexef'.hex()<br>Out[1]: 'deadbeef'<br>
To convert the hex string back to bytes, use the bytes.fromhex() method:
<br>In [2]: bytes.fromhex('deadbeef')<br>Out[2]: b'xdexadxbexef'<br>
This method is also compatible with mutable bytearray types:
<br>In [3]: bytearray(b'xdexadxbexef').hex()<br>Out[3]: 'deadbeef'<br>In [4]: bytes.fromhex('deadbeef')<br>Out[4]: bytearray(b'xdexadxbexef')<br>
For your convenience, here's the complete documentation for the hex() and fromhex() methods:
The above is the detailed content of How to Convert Bytes to Hex Strings and Vice Versa in Python 3?. For more information, please follow other related articles on the PHP Chinese website!