Home >Backend Development >Python Tutorial >How Can I Efficiently Convert Bytes to Hex Strings and Back in Python 3?
Converting Bytes to Hex Strings in Python 3
When working with bytes in Python 3, converting them into hex strings can be a common task. Despite the availability of various approaches, some methods may not yield the desired results.
The Modern Solution: .hex()
Python 3.5 introduced a dedicated method, bytes.hex(), which simplifies this conversion:
>>> b'\xde\xad\xbe\xef'.hex() 'deadbeef'
This method returns a hexadecimal representation of the bytes.
Reversing the Conversion
To convert a hex string back to bytes, you can use bytes.fromhex():
>>> bytes.fromhex('deadbeef') b'\xde\xad\xbe\xef'
This method accepts a hexadecimal string and returns a byte array. The conversion supports both the bytes and bytearray types.
Additional Considerations
Note that this method operates on binary data and not strings. If you have a string, you may need to encode it to bytes first, for example, using bytes(string, 'utf-8').
The above is the detailed content of How Can I Efficiently Convert Bytes to Hex Strings and Back in Python 3?. For more information, please follow other related articles on the PHP Chinese website!