Huffman coding (Java)

This project is an open source reference implementation of Huffman coding in Java. The code is intended to be used for study, and as a solid basis for modification and extension. As such, it is optimized for clear logic and low complexity, not speed/memory/performance.

Overview

Huffman encoding takes a sequence (stream) of symbols as input and gives a sequence of bits as output. The intent is to produce a short output for the given input. Each input yields a different output, so the process can be reversed, and the output can be decoded to give back the original input.

In this software, a symbol is a non-negative integer. The symbol limit is one plus the highest allowed symbol. For example, a symbol limit of 4 means that the set of allowed symbols is {0, 1, 2, 3}.

Sample applications

Two pairs of command line programs fully demonstrate how this software package can be used to encode and decode data using Huffman coding. One pair is the classes HuffmanCompress and HuffmanDecompress, which implements static Huffman coding. The other pair is the classes AdaptiveHuffmanCompress and AdaptiveHuffmanDecompress, which implements adaptive/dynamic Huffman coding.

Encoder/decoder

The classes HuffmanEncoder and HuffmanDecoder implement the basic algorithms for encoding and decoding a Huffman-coded stream. The code tree must be set before encoding or decoding. The code tree can be changed after encoding or decoding each symbol, as long as the encoder and decoder have the same code tree at the same time. At any time, the encoder must not attempt to encode a symbol that is not in the code tree.

Huffman code tree

The class CodeTree, along with Node, InternalNode, and Leaf, represent a Huffman code tree. The leaves represent symbols. The path to a leaf represents the bit string of its Huffman code.

Frequency table

The class FrequencyTable is a simple integer array wrapper that counts symbol frequencies. It is also responsible for generating a Huffman code tree that is optimal for its current array of frequencies (but not necessarily canonical).

Canonical codes

The class CanonicalCode converts an arbitrary CodeTree to a canonical code. It can then generate a CodeTree for the canonical code.

Bitwise I/O streams

The classes BitInputStream and BitOutputStream are I/O streams based on bitwise I/O, analogous to the standard bytewise I/O streams. However, they use an underlying bytewise I/O stream, so they can only work with bitwise streams whose length is a multiple of 8 bits.

Download

Browse the project’s source code is available at GitHub: https://github.com/nayuki/Huffman-Coding

Or download a ZIP of all the files: https://github.com/nayuki/Huffman-Coding/zipball/master

The code is open source under the MIT License. See the readme file for details.

Limitations

Suggestions

Here are some suggestions on how to use, modify, or extend this software:

More info