Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is binascii.b2a_hqx in Python?

Sarvech Qadir

The binascii is a widely used Python library for ASCII-encoded binary representations. It contains several methods for converting to binary from ASCII or hex, and vice versa.

We use binascii.b2a_hqx for binary-to-ASCII translation in hexbin4 format. The method returns the resulting string. In order to use this function, we need to note a few things.

  1. The string parameter should be RLE-codedRun-length encoding (RLE) is a lossless compression technique to store the count of consecutive characters. For example, “Hellllooooo” translates to “Hel-4o-5”, showing that 'l occurs 4 times and ‘o’ occurs five times.
  2. The length of string should be divisible by 3.

This function works in opposite to the a2b_hqx() method.

Syntax

binascii.b2a_hqx(data)

This method returns a binary string.

Code

Let’s work through a few coding examples using b2a_hqx.

import binascii

data = "Hello World"

## convert to binary
text_bytes = bytes(data,'utf-8')
## perform b2a_hqx
print(data, "==>", binascii.b2a_hqx(text_bytes))

data1 = "Welcome to educative"
## convert to binary
text_bytes1 = bytes(data1,'utf-8')
## perform b2a_hqx
print(data1, "==>", binascii.b2a_hqx(text_bytes1))

RELATED TAGS

python

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring