Huffman file compressor
Compress and decompress real text files with Huffman coding and show how much space you saved.
Advancedâą 10â14 hoursđĒ 7 stepsC++ or Java or PythonPriority queueBits
What you'll learn
- âGreedy algorithms and priority queues
- âBinary trees and prefix codes
- âBit-level file I/O
What you'll build
- âcompress file.txt â file.huf
- âdecompress back to the exact original
- âPrints compression ratio
- âHandles any byte, not just letters
Step-by-step guide
- 1
Count frequencies
Read the file as bytes; count each of the 256 values.
- 2
Build the tree
Push a leaf per byte into a min-heap by frequency; repeatedly pop two, join them under a new node, push back.
- 3
Make codes
Walk the tree: left = 0, right = 1; store the code string for each byte.
- 4
Write bits
Pack codes into bytes with a bit buffer; write a header with the frequency table and the original length.
- 5
Decompress
Rebuild the tree from the header, read bits, walk from the root to a leaf, output the byte, repeat.
- 6
Verify
Compare the original and decompressed files byte by byte (or with a hash).
- 7
Measure
Report sizes and ratio; try a text file, an image and an already zipped file and explain the results.
đ Make it stand out
- +Canonical Huffman codes for a smaller header
- +Compare with gzip
- +Add a progress bar for big files