Built in 2019
Compressor
File Compressor
Linux console application that allows to compress and decompress files using the Huffman algorithm made to practice the manipulation of bit operations.
Made with
In a normal text file, the letter ‘e’ and the letter ‘z’ both take 8 bits. Yet ‘e’ appears 57 times more often in English text. Every character costs the same, even though some show up far more than others. Text files waste a lot of space.
David Huffman found the fix in 1952. Give common characters short codes and rare characters long codes. The average code gets shorter, and the file shrinks.
I wanted to understand this at the level of single bits. I did not want a library. I wanted to write every bit operation myself. Compressor was that exercise.
Two commands, one format
Compressor is a Linux command line tool written in C. It compresses and decompresses files with Huffman coding. You use it like this:
./compressor zip input.txt # Creates input.txt.rol
./compressor unzip input.txt.rol # Restores input.txt
Compressed files get a custom .rol extension. The tool reads any file type. It works best on text files, where some characters repeat far more than others.
Short codes for common letters
The algorithm builds a binary tree. Frequent characters sit near the root, and rare ones sit deeper in the leaves. Each character gets a unique binary code from its path from the root to its leaf. A left branch adds a 0. A right branch adds a 1.
Take a file that holds only “AAABBC”. A appears 3 times, B 2 times and C 1 time. Without compression, it takes 48 bits (6 characters times 8 bits). With Huffman coding, A might get the code 0 (1 bit), B gets 10 (2 bits) and C gets 11 (2 bits). The encoded data, 0 0 0 10 10 11, takes 9 bits.
Four stages to compress
Compressing a file happens in four stages.
Stage 1: Frequency Analysis
The program reads the whole file and counts how many times each byte value appears. A linked list stores each unique character and its count.
Stage 2: Tree Construction
The algorithm sorts the characters by frequency. Then it takes the two nodes with the lowest counts and creates a parent node with their combined count. It puts that parent back in the list. It repeats this until one node is left. That node is the root of the Huffman tree.
Stage 3: Code Generation
A recursive walk through the tree gives each character its binary code. Going left adds a 0 bit. Going right adds a 1 bit. The codes go into a lookup table so encoding is fast.
Stage 4: Encoding
The program reads the original file again. For each character, it looks up the bit code and writes those bits to the output file. The compressed file also stores the code table at the start, so the decompressor can rebuild the tree.
C only writes bytes
This is where the project got interesting. C has no “write 3 bits” function. You work with whole bytes. To write any sequence of bits, you collect them in a buffer and write each full byte to the file.
The encoder keeps a 32 bit accumulator, a holding area for bits, plus a count of how many bits it holds. To encode a character, it shifts the accumulator left by the code length and ORs in the new bits. OR is the operation that merges two bit patterns. When the accumulator holds 8 or more bits, the encoder writes the top byte to the file.
Shift operations do most of the work:
bits << nmultiplies by 2^n, which makes room for new bitsbits | codecombines the collected bits with the new onesbits >> npulls out the top bits for writing
The decompressor does the reverse. It reads bytes into a buffer, then takes one bit at a time to walk the Huffman tree. Each bit says go left or go right. When it reaches a leaf, it writes that character and starts again from the root.
A header to rebuild the tree
The compressed file starts with metadata:
- Number of unique characters (1 byte)
- Total character count in original file (8 bytes)
- For each unique character:
- The character (1 byte)
- Code length (1 byte)
- The binary code (8 bytes)
The compressed data comes after the header. The decoder reads the header first and rebuilds the Huffman tree from the codes. Then it decodes the data with that tree.
Bytes in the wrong order
Machines store numbers of several bytes in different orders. This is called endianness. x86 processors are little endian, which means they store the least significant byte first. The code handles the byte order on purpose when it reads 32 bit values:
unsigned long maskA = bits & 0x000000FFUL;
unsigned long maskB = bits & 0x0000FF00UL;
unsigned long maskC = bits & 0x00FF0000UL;
unsigned long maskD = bits & 0xFF000000UL;
maskA <<= 24;
maskB <<= 8;
maskC >>= 8;
maskD >>= 24;
return maskA + maskB + maskC + maskD;
This code reverses the byte order. The decoder reads the bits correctly on any machine architecture.
Every shift is yours
Writing a compressor from scratch showed me how data really lives in memory. High level languages hide the difference between bytes and bits. In C, you control every shift and every mask.
The Huffman algorithm is elegant. A simple frequency count and a greedy way of building the tree produce prefix codes that are provably optimal. No code is the start of another code, so decoding never has two possible answers.
The project also showed me why compression libraries exist. Edge cases pile up. What about empty files? Files with only one unique character? Binary files that use all 256 byte values? Handling each one correctly takes care.
I still use what I learned here when I think about binary protocols, network packets and file formats. Once you understand bits, the rest gets clearer.
GitHub - RolandoAndrade/compressor: Aplicación de consola que permitir comprimir y descomprimir archivos mediante el algoritmo de Huffman realizado para practicar la manipulación de las operaciones de bit Aplicación de consola que permitir comprimir y descomprimir archivos mediante el algoritmo de Huffman realizado para practicar la manipulación de las operaciones de bit - RolandoAndrade/compressor If you are curious about low level programming or data compression, build a Huffman encoder over a weekend. The algorithm fits in a few hundred lines, and the bit manipulation teaches lessons that stay with you.
Interested in working together? Check out my services and pricing to see how we can collaborate on your next project. Let's Build