Python .b2a_hex()
Anonymous contributor
Published Oct 14, 2025
Contribute to Docs
The .b2a_hex() function converts binary data into a bytes object containing a string of ASCII characters representing the data in Base16 (hexadecimal) format.
Syntax
binascii.b2a_hex(data[, sep[, bytes_per_sep=1]])
Parameters:
data: The binary data to convert. Must be abytesorbytearrayobject.sep(optional): A single-byte separator inserted between pairs of hex digits in the output.bytes_per_sep(optional, default = 1): Determines how many bytes are grouped together before inserting the separator. Ignored ifsepis not provided.
Return value:
Returns a bytes object containing the hexadecimal (Base16) ASCII representation of the input binary data.
Example: Basic Hexadecimal Conversion
In this example, the binary string "hello" is converted to its Base16 ASCII representation:
import binascii# Create binary data to encodebinary_data = b"hello"# Encode the binary data to Base16 ASCII formatencoded_data = binascii.b2a_hex(binary_data)print(encoded_data)
This produces the following output:
b'68656c6c6f'
Note: Each byte of the input is converted to its two-character hexadecimal representation.
Codebyte Example
In this example, the binary string "Codecademy" is converted to hexadecimal using .b2a_hex() to demonstrate encoding in a small, real-life scenario:
All contributors
- Anonymous contributor
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