Inside Macintosh: Operating System Utilities /
Chapter 3 - Mathematical and Logical Utilities / Mathematical and Logical Utilities Reference
Routines / Compressing and Decompressing Data

### PackBits

You can use the PackBits procedure to compress a data buffer stored in RAM.

PROCEDURE PackBits (VAR srcPtr, dstPtr: Ptr; srcBytes: Integer);
srcPtr
On entry, a pointer to the first byte of a buffer of data to be compressed. On exit, a pointer to the first byte following the bytes compressed.
dstPtr
On entry, a pointer to the first byte in which to store compressed data. On exit, a pointer to the first byte following the compressed data.
srcBytes
The number of bytes of uncompressed data to be compressed. In versions of software prior to version 6.0.2, this number must be 127 or less.
##### DESCRIPTION
The PackBits procedure compresses srcBytes bytes of data beginning at the location specified by the srcPtr parameter and stores it at the location specified by the dstPtr parameter. It then modifies the srcPtr and dstPtr variables to point to the first bytes after the uncompressed and compressed data, respectively.

Your application must allocate memory for the destination buffer itself. In general, you should allocate enough memory for a worst-case scenario. In the worst case, the destination buffer is 128 bytes long for each block of source data up to 127 bytes. Thus, you can use the following formula to determine how much space to allocate for the destination buffer:

maxDstBytes := srcBytes + (srcBytes+126) DIV 127;
where maxDstBytes stands for the maximum number of destination bytes.

The PackBits algorithm is most effective on data buffers in which there are likely to be series of bytes containing the same value. For example, resources of many formats often contain many consecutive zeros. If you have a data buffer in which there are only likely to be series of words or long words containing the same value, PackBits is unlikely to be effective.

Because your application must allocate memory for the source and destination buffers, PackBits does not move relocatable blocks. Thus, you can call it at interrupt time.

##### SPECIAL CONSIDERATIONS
Because PackBits changes the values of the srcPtr and dstPtr parameters, you should pass to PackBits only copies of pointers to the source and destination buffers. This allows you to access the beginning of the source and destination buffers after PackBits returns. Also, if the source or destination buffer is stored in an unlocked, relocatable block, this technique prevents PackBits from changing the value of a master pointer, which would make the original handle invalid.