Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is binascii.rlecode_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 often use binascii.rlecode_hqx to perform binhex4 style RLE-compression on the data. It utilizes a simple mechanism to compress the data.

Given an input, say “Helloooooooo”, the function iterates through the string to check for consecutive characters. In this case, there are 8 consecutive “o’s”. The function will compress this and show the output with a single o followed by \x90\x and then number of times it occurred. This function is the opposite of rledecode_hqx() method.

The compression only occurs if the consecutive characters are greater than or equal to 4.

Syntax

binascii.rlecode_hqx(data)

Code

Let’s work through a few examples of binascii.rlecode_hqx. In this example, we use ‘HelloooooooWWWWWWorldddd’ as an input to the rlecode_hqx method.

Given this input:

  1. There are 7 consecutive o’s
  2. There are 6 consecutive W’s
  3. There are 6 consecutive d’s

The output will contain the following features:

  1. The output gives the Hello-first occurrence of o followed by the count 07.

  2. The output gives the W-first occurrence of W followed by the count 06.

  3. The output gives the orld-first occurrence of d followed by the count 04.

import binascii
# Given this input:
# there are 7 consecutive o's.
# there are 6 consecutive W's.
# there are 6 consecutive d's.


rle = binascii.rlecode_hqx(b'HelloooooooWWWWWWorldddd')
print(rle)

# The output gives the Hello-first occurence of o followed
# by the count 07. 

# The output gives the W-first occurence of W followed
# by the count 06. 

# The output gives the orld-first occurence of d followed
# by the count 04. 


# in this example, compression does not occur as 4-rule
# is not applied
rle1 = binascii.rlecode_hqx(b'Welcome')
print(rle1)

RELATED TAGS

python

CONTRIBUTOR

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

View all Courses

Keep Exploring