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.
binascii.rlecode_hqx(data)
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:
The output will contain the following features:
The output gives the Hello-first
occurrence of o
followed
by the count 07.
The output gives the W-first
occurrence of W
followed
by the count 06.
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
CONTRIBUTOR
View all Courses