Pack, UnPack Function

Purpose

Compresses a string at byte level

Syntax

$ = Pack[$](string [,flag = 0])

$ = UnPack[$](string)

string:sexp
flag:iexp

Description

The Pack function returns a compressed string from another string. The function UnPack decompresses the string compressed with Pack.

Pack will place a 12 byte label in front of a compressed string. The first four signs are "PCK0" (PeCehKahZero), after this, four more signs follow with the length of the compressed data and last four with the original length:

"PCK0" + Mkl$(length_after_compression) + Mkl$(original length) + packed data

When both the original data size as the compressed data size are smaller than 65536, a header of 8 bytes is used, with a lowercase k instead of K, and both lengths in a 16-bit value. Data that cannot be compressed (random byte sequences or a Crypt$) are marked with a lowercase c, followed by only one length (k=16 bit, K=32 bit), so 6 or 8 bytes.

The optional flag can have a value of 0, 1, or 2. If flag = 1 an additional bit pack run is performed. This run will take a bit of time, but as a result, you get a better compression rate (1-10%, sometimes more). In addition, plain text snippets are mostly removed from the compressed string. Packing with default value of flag (= 0) often results in a compressed string where words might be readable. A packed string with flag is 1 is marked as PCK1 or PCk1 instead of PCK0.

flag = 2 forces a bit pack, whether or not the packed string becomes longer.

Example

OpenW 1

Local a$, b$, c$, d$, b%, x%

Local e$, f$, g$

// Write 1000 times Hello

For b% = 0 To 9999

a$ = a$ + "Hello"

Next

// Pack with flag 0,1,2

b$ = Pack(a$, 0)

c$ = Pack(a$, 1)

d$ = Pack(a$, 2)

// Show the length of the strings

Print Len(a$), Len(b$), Len(c$), Len(d$)

// Unpack the strings

e$ = UnPack(b$)

f$ = UnPack(c$)

g$ = UnPack(d$)

Print Len(a$), Len(e$), Len(f$), Len(g$)

Print a$ = e$, a$ = f$, a$ = g$

Remarks

The compression rate of Pack compares to ARC, the grand father of all compression programs, or Compress the program from Microsoft.

Known Issues

Pack throws an Access error if the string to be packed is a null string (""); if this is likely to occur in your program, it is best to either use the function within a Try....Catch structure or use code similar to this:

Local a$ = ""

Local b$ = Iif(a$ = "", "", Pack(a$))

UnPack is unaffected by this error; in other words, UnPack("") simply retruns a null string.
[Reported by Roger Cabo, 04/10/2022]

See Also

PackMem

{Created by Sjouke Hamstra; Last updated: 06/10/2022 by James Gaite; Other Contributors: Roger Cabo}