Home  >  Article  >  Backend Development  >  How to Easily Convert Bytes to Hex and Back in Python 3?

How to Easily Convert Bytes to Hex and Back in Python 3?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 13:04:01225browse

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!

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