Python .a2b_hex()

Anonymous contributor's avatar
Anonymous contributor
Published Oct 29, 2025
Contribute to Docs

The binascii.a2b_hex() function in Python decodes a hexadecimal (base-16) encoded ASCII string into its original binary form. It translates pairs of hexadecimal digits into corresponding byte values, effectively reversing the process of hex encoding.

  • 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

Syntax

binascii.a2b_hex(string)

Parameters:

  • string: A bytes or bytearray object containing hexadecimal (base-16) encoded data. Each pair of hex digits represents one byte, so the length must be even.

Return value:

Returns a bytes object containing the binary data decoded from the given hexadecimal input.

Exceptions:

Raises binascii.Error if the input contains an odd number of hexadecimal digits or contains invalid characters.

Example

In this example, the hexadecimal string "48656C6C6F" is decoded into its corresponding binary data and then interpreted as ASCII text:

import binascii
# Convert hexadecimal string to binary
hex_string = "48656C6C6F"
binary_data = binascii.a2b_hex(hex_string)
print("Hexadecimal:", hex_string)
print("Binary data:", binary_data)
print("Decoded text:", binary_data.decode('utf-8'))

The output of this code is:

Hexadecimal: 48656C6C6F
Binary data: b'Hello'
Decoded text: Hello

Codebyte Example

Run the following code to see .a2b_hex() in action with different scenarios:

Code
Output
Loading...

All contributors

Contribute to 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