Sub topic 1
Why Fixed-Length Codes Waste Bits
Every compression scheme starts by asking how many bits each piece of data really needs. The simplest answer gives every symbol the same number of bits. That answer is easy to build and easy to decode, and it is almost always wasteful. This chapter measures that waste and shows where it comes from. The rest of the tutorial builds on that idea.
Prerequisites
This chapter assumes you are comfortable with:
- Binary numbers, bits, and how many values
nbits can represent (2^n). - Basic Python: dictionaries, loops, string methods, and
collections.Counter. - Logarithms base 2 at the level of "log2(8) = 3".
- Basic probability: turning counts into proportions.
Binary trees and min-heaps become important in later chapters. You don't need them here.
The fixed-length model
A fixed-length code assigns every symbol a bit pattern of the same width w. ASCII is the familiar example. Each character takes 8 bits, so a message of n characters takes exactly 8n bits.
Fixed width gives you three properties for free:
- No separators. The decoder reads
wbits, looks up the symbol, and repeats. - Random access. Symbol
istarts at biti * w, so you can jump straight to it. - No table to ship when everyone already agrees on the code, as with ASCII.
Fixed-length codes are not wrong. Their cost is that they ignore two facts about real data, and each fact wastes bits in its own way.
Waste source 1: an oversized alphabet
ASCII reserves 256 patterns per byte. A message that uses only 5 distinct characters needs far fewer. With k distinct symbols, the narrowest fixed-length code that works has width:
w = ceil(log2(k)), with a minimum of 1 bit
For k = 5, that is 3 bits. Three bits give 8 patterns, and only 5 of them are used. The other 3 patterns are never sent, yet every symbol still pays for the capacity they represent.
| Distinct symbols (k) | Minimum fixed width | Patterns available | Patterns unused |
|---|---|---|---|
| 2 | 1 | 2 | 0 |
| 5 | 3 | 8 | 3 |
| 8 | 3 | 8 | 0 |
| 26 | 5 | 32 | 6 |
| 100 | 7 | 128 | 28 |
When k is a power of two, nothing is wasted at this level. When k sits just above a power of two, as with 17 symbols needing 5 bits, almost half the patterns go unused. The information-theoretic cost of choosing one of k equally likely symbols is log2(k) bits. That value is usually fractional (log2(5) ≈ 2.32), and a fixed whole-bit width has to round it up.
Waste source 2: ignoring frequency
The bigger loss comes from treating all symbols as equally common. Real data is skewed. In English text, e appears far more often than z. In a log file, a few characters such as spaces, digits, and newlines dominate. A fixed-length code spends exactly as many bits on the rarest symbol as on the most common one.
Take the message abracadabra. It has 11 characters and 5 distinct symbols:
| Symbol | Count |
|---|---|
| a | 5 |
| b | 2 |
| r | 2 |
| c | 1 |
| d | 1 |
a makes up almost half the message. Giving it a 1-bit code and the others 3-bit codes uses fewer bits in total, even though some symbols get longer than the fixed width would have made them:
| Symbol | Count | Fixed code (3 bits) | Variable code | Fixed bits | Variable bits |
|---|---|---|---|---|---|
| a | 5 | 000 | 0 | 15 | 5 |
| b | 2 | 001 | 100 | 6 | 6 |
| r | 2 | 010 | 101 | 6 | 6 |
| c | 1 | 011 | 110 | 3 | 3 |
| d | 1 | 100 | 111 | 3 | 3 |
| Total | 11 | 33 | 23 |
The 3-bit fixed code takes 33 bits. The variable-length code takes 23. All of the saving comes from a. Because the code is shorter where the data is dense, the message shrinks by 30%. Against plain 8-bit ASCII at 88 bits, the variable code saves about 74%.
Measuring it in code
The script below computes all three totals. It uses int.bit_length in place of math.log2 to find the minimum width, which avoids floating-point rounding and handles the one-symbol case.
from collections import Counter
def min_fixed_width(k):
"""Smallest whole number of bits that gives k distinct patterns (at least 1)."""
return max(1, (k - 1).bit_length())
def fixed_length_bits(text):
width = min_fixed_width(len(set(text)))
return width, width * len(text)
def variable_length_bits(text, codes):
return sum(len(codes[ch]) for ch in text)
text = "abracadabra"
codes = {"a": "0", "b": "100", "r": "101", "c": "110", "d": "111"}
width, fixed_total = fixed_length_bits(text)
variable_total = variable_length_bits(text, codes)
print("Counts:", dict(Counter(text)))
print("ASCII:", 8 * len(text), "bits")
print(f"Fixed {width}-bit:", fixed_total, "bits")
print("Variable:", variable_total, "bits")
print(f"Average bits/symbol: fixed={fixed_total / len(text):.3f}, "
f"variable={variable_total / len(text):.3f}")Output:
Counts: {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
ASCII: 88 bits
Fixed 3-bit: 33 bits
Variable: 23 bits
Average bits/symbol: fixed=3.000, variable=2.091The last line gives the metric this tutorial uses from here on: average bits per symbol. It equals the sum, over all symbols, of each symbol's probability times its code length. A fixed-length code always has an average equal to its width. A variable-length code can get its average below that width by matching code lengths to frequencies.
The catch: variable lengths need care
Once codes differ in length, the decoder no longer knows where one symbol ends and the next begins. The code above works because no code word is the start of another. For example, 0 is not the beginning of 100, 101, 110, or 111. Suppose you chose a = 0 and b = 01 instead. Then the bits 01 could mean b, or a followed by the start of something else. The chapter on prefix-free codes covers this property. Huffman's algorithm builds such a code automatically and picks the lengths that minimize the total.
When fixed length still wins
Variable-length coding is a trade-off. Some cases favor the fixed approach:
- Uniform data. If every symbol is equally likely and
kis a power of two, a fixed code is already optimal. Already-compressed or encrypted bytes look like this, which is why compressing a ZIP file again rarely helps. - Random access. Variable-length streams have to be decoded from the start, or from saved checkpoints.
- Table overhead. The decoder must learn the variable code. For a 20-byte message, describing the code can cost more than the saving. A later chapter shows how canonical codes keep this overhead small.
- Speed and simplicity. Fixed-width decoding is a shift and a mask. Variable-width decoding needs bit-level parsing.
Common errors
- Counting the full ASCII width as the baseline for everything. The fair fixed-length baseline uses ceil(log2(k)) bits, not 8. Comparing against ASCII overstates the gain from variable-length coding.
- Forgetting the one-symbol case. log2(1) = 0, but a code still needs at least 1 bit per symbol, or a length count, so the decoder knows how many symbols there are.
- Assuming variable length always helps. With a flat distribution it gains nothing, and the code table makes the output larger.
- Ignoring the code description. The true compressed size is the bitstream plus whatever the decoder needs to rebuild the code.
Exercise
A message uses 17 distinct symbols. What is the minimum fixed-length width, and what fraction of the available bit patterns go unused?
Show answer
ceil(log2(17)) = 5 bits, giving 32 patterns. 32 - 17 = 15 are unused, about 47% of the code space.
Exercise
The text "abcdabcdabcd" has 4 symbols, each appearing 3 times. Can any variable-length prefix-free code beat the 2-bit fixed code in total bits? Explain.
Show answer
No. With 4 equally likely symbols, the best achievable average is log2(4) = 2 bits per symbol, which the fixed 2-bit code already reaches. Making one code shorter forces another to be longer, so the total is never below 24 bits.
Exercise
The text "aaaaaaab" has 7 a's and 1 b. What does the fixed-length code cost? Can a symbol-by-symbol variable-length code do better?
Show answer
k = 2, so the fixed width is 1 bit and the total is 8 bits. Every symbol needs at least 1 bit in a symbol-by-symbol code, so no such code can beat 8 bits, even though the data is very skewed. This whole-bit limit returns in the chapter on limitations.
Exercise
Using the code a=0, b=100, r=101, c=110, d=111, how many bits does "abba" take, and how does that compare with the 3-bit fixed code?
Show answer
a(1) + b(3) + b(3) + a(1) = 8 bits, against 4 × 3 = 12 bits for the fixed code.