Introduced
This article describes the simplest and fastest Huffman coding that can be found on the Internet. This method does not use any extended dynamic libraries, such as STL or component. Use simple C functions, such as: Memset,memmove,qsort,malloc,realloc and memcpy.
As a result, everyone will find it easy to understand or even modify the code.
Background
Huffman compression is a lossless compression algorithm, generally used to compress text and program files. Huffman compression belongs to the variable code length algorithm family. An individual symbol (for example, a character in a text file) is substituted with a bit sequence of a specific length. As a result, there are high frequency symbols in the file, using short bit sequences, and those that rarely appear, with longer bit sequences.
Encoding use
I write this code in a simple C function to make it easy to use anywhere. You can put them in a class, or use this function directly. And I used a simple format, just to input the output buffer, not as in other articles, input output file.
bool CompressHuffman(BYTE *pSrc, int nSrcLen, BYTE *&pDes, int &nDesLen);
bool DecompressHuffman(BYTE *pSrc, int nSrcLen, BYTE *&pDes, int &nDesLen);
Important Notes
Speed
It took me a long time to get it to run fast (huffman.cpp). At the same time, I do not use any dynamic libraries, such as STL or MFC. It compresses 1M data less than 100ms (P3 processor, 1G).
Compression
The compression code is very simple, first initializes 511 Huffman nodes with the ASCII value:
CHuffmanNode nodes[511];
for(int nCount = 0; nCount < 256; nCount++)
nodes[nCount].byAscii = nCount;
Then, calculate how often each ASCII code appears in the input buffer data:for(nCount = 0; nCount < nSrcLen; nCount++)
nodes[pSrc [nCount]].nFrequency++;
Then, sort by frequency:qsort (nodes, 256, sizeof(CHuffmanNode), frequencyCompare);
Now, construct Huffman tree to get the bit sequence corresponding to each ASCII code:int nNodeCount = GetHuffmanTree(nodes);
The Construction Huffman tree is very simple, put all the nodes in a queue, replace two nodes with one node, and the frequency of the new nodes is the sum of the frequencies of the two nodes. In this way, the new node is the parent node of the two replaced nodes. This loops until only one node (tree root) is left in the queue.// parent node
pNode = &nodes[nParentNode++];
// pop first child
pNode- >pLeft = PopNode(pNodes, nBackNode--, false);
// pop second child
pNode->pRight = PopNode(pNodes, nBackNode--, true);
// adjust parent of the two poped nodes
pNode->pLeft- >pParent = pNode->pRight->pParent = pNode;
// adjust parent frequency
pNode->nFrequency = pNode->pLeft- >nFrequency + pNode->pRight->nFrequency;