Python .hexlify()
The .hexlify() method from Python’s binascii module encodes binary data into a hexadecimal (base-16) ASCII representation. It’s an alias for binascii.b2a_hex() and is commonly used to represent binary data in a readable hex format. Each byte of input data is converted into a two-digit hexadecimal value.
Syntax
binascii.hexlify(data[, sep[, bytes_per_sep]])
Parameters:
data(bytes-like): The binary data to encode.sep(optional, single characterstrorbytes): A separator to insert between hex groups.bytes_per_sep(optionalint): After everybytes_per_sepinput bytes, insertsep. A negative value will count from the right end.
Return value:
Returns a bytes object containing the hexadecimal ASCII representation of the input.
Note: The returned object is always twice as long as the original data. If
sepis provided, it’s inserted at the specified intervals for better readability.
Example: Converting Binary Data to Hexadecimal
This example encodes a byte string into its hexadecimal equivalent:
import binasciimessage = b'Python3'hex_value = binascii.hexlify(message)print(hex_value)
The output of this code is:
b'507974686f6e33'
This converts each byte of 'Python3' into a two-character hexadecimal value, producing a readable byte representation.
Codebyte Example: Converting to Hexadecimal and Decoding to String
This codebyte demonstrates converting binary data into its hexadecimal representation using .hexlify():
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours