Introduction
Huffman coding is the entropy-coding stage of ZIP, PNG and JPEG. This project implements a complete compressor and decompressor that work on any file, with a compact header that lets the decoder rebuild the exact same tree.
Problem statement
Objectives
- Build a Huffman tree with a binary min-heap
- Write and read individual bits
- Design a portable binary file format
- Handle edge cases and errors precisely
Features
- compress / decompress / codes / demo modes
- Deterministic trees (tie-breaking)
- Header stores only symbols that occur
- Single-symbol and empty file support
- Round-trip verification
Concepts demonstrated
- Greedy algorithms
- Priority queues
- Bit manipulation
- Endianness
- File formats
System architecture
Pass 1 counts byte frequencies. build_tree pushes one leaf per symbol into a min-heap and repeatedly merges the two lightest nodes. assign_codes walks the tree to build code strings. Pass 2 writes the header (magic, size, symbol table) and packs code bits MSB-first into bytes. Decompression reads the header, rebuilds the identical tree and walks it bit by bit.
Folder structure
Complete source code
Makefile
What each file does
- src/huffman.h
- The file format description, stats struct and API.
- src/huffman.c
- Min-heap, tree building, code assignment, little-endian helpers, compress, decompress and the code table.
- src/main.c
- Command-line modes and round-trip verification.
- Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
Testing
./app demo sample.txtmust matchtests/expected-output.txtand report "round trip OK".- Compress an image or a PDF and decompress it; compare with
cmp(Linux/macOS) orfc /b(Windows). - Compress an empty file and a file containing only "aaaa".
Common errors
Decompressed file has extra bytes
Stop decoding after original_bytes symbols; the last byte contains padding bits.
Files compressed on one machine fail on another
Write integers byte by byte in a fixed order (as write_u32/write_u64 do), never with fwrite of an int.
Possible improvements
- Store the tree shape instead of frequencies for a smaller header
- Canonical Huffman codes
- Stream large files in blocks
Additional challenges
- 1Add LZ77 before Huffman coding to build a mini-DEFLATE.
- 2Measure compression ratios on text, source code and images, and explain the differences.
- 3Add a checksum (CRC-32) to detect corrupted files.
Built and tested it yourself? Mark it to update your dashboard.