Bit-Packing Order for GIF LZW Codes

This article explains the precise bit-packing scheme used to serialize variable-length LZW codes into byte streams within GIF data sub-blocks. In the GIF specification (GIF87a and GIF89a), variable-width LZW codes are written into bytes using a Least Significant Bit (LSB) first convention. This guide details how individual code bits map across byte boundaries and how the resulting bytes are organized inside sub-blocks.

LSB-First Bit Packing

LZW codes in GIF are variable in length, starting at code_size + 1 bits (where code_size is the LZW Minimum Code Size, at least 2) and expanding dynamically up to a maximum of 12 bits.

When packing these arbitrary-length codes into 8-bit bytes:

  1. Bit Placement: The least significant bit (LSB) of the LZW code is mapped to the lowest unused bit (starting at bit 0) of the current byte.
  2. Byte Saturation: Successive bits of the code fill the current byte upward toward the most significant bit (bit 7).
  3. Byte Spanning: When an LZW code contains more bits than remain in the current byte, the lower bits of the code fill the remainder of the current byte up to bit 7. The byte is then emitted, and the remaining higher-order bits of the code are placed starting at bit 0 of the next byte.

Step-by-Step Packing Example

Assume the current code width is 5 bits, and the encoder outputs two consecutive 5-bit codes:

Packing Code A:

Packing Code B:

Sub-Block Encapsulation

The stream of packed 8-bit bytes is not written continuously across the entire image. Instead, it is partitioned into discrete data sub-blocks:

When the encoder outputs the final code (the End of Information code, or EOI), any partially filled final byte is padded with zero bits up to bit 7 and emitted into the current sub-block before writing the 0x00 terminator.