Home >Backend Development >Python Tutorial >How to Convert Bytes to Hex Strings and Vice Versa in Python 3?

How to Convert Bytes to Hex Strings and Vice Versa in Python 3?

Linda Hamilton
Linda HamiltonOriginal
2024-12-09 17:40:18819browse

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:

  • https://docs.python.org/3/library/stdtypes.html#bytes.hex
  • https://docs.python.org/3/library/stdtypes.html#bytes.fromhex

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn