LZW词典编解码

本文详细介绍了LZW编码算法的实现过程,包括字典初始化、节点结构、编码与解码步骤,以及使用C语言实现的代码示例。通过对不同文件类型的压缩测试,展示了LZW算法在某些文件格式上的压缩优势,同时也指出其在现有压缩格式中的局限性,暗示了优化空间。
摘要由CSDN通过智能技术生成

LZW编码算法的步骤如下:

步骤1:将词典初始化为包含所有可能的单字符,当前前缀P初始化为空。

步骤2:当前字符C=字符流中的下一个字符。

步骤3:判断P+C是否在词典中

         (1)如果“是”,则用C扩展P,即让P=P+C,返回到步骤2。

         (2)如果“否”,则输出与当前前缀P相对应的码字W;将P+C添加到词典中;令P=C,并返回到步骤2

数字查找树

节点结构体:

struct {
  int suffix;
  int parent, firstchild, nextsibling;
} node

初始化:

void InitDictionary( void){
	int i;
	for( i=0; i<256; i++){
		dictionary[i].suffix = i;   // 每一个ASCII字符
		dictionary[i].parent = -1; // 因为是第一级节点,所以没有上级节点
		dictionary[i].firstchild = -1; // 还没有添加子节点
		dictionary[i].nextsibling = i+1; // 右侧相邻的子节点
	}
	dictionary[255].nextsibling = -1; // 最后一个ASCII字符,第一级的最后一个节点,没有下一个相邻的节点了
	next_code = 256; // 新节点会一次放到dictionary列表的后面
}

 向数字查找树中添加新节点:

void AddToDictionary( int character, int string_code){  // 把character挂到string_code后面
	int firstsibling, nextsibling;   				   
	if( 0>string_code) return;	//	string_code不合法
	dictionary[next_code].suffix = character;		// 把新节点放入词典中,
	dictionary[next_code].parent = string_code;     // 父节点是string_code
	dictionary[next_code].nextsibling = -1;         // 先不考虑邻居
	dictionary[next_code].firstchild = -1;		    // 没有子节点
	firstsibling = dictionary[string_code].firstchild;   // 查找string_code下已经挂了哪些节点,要把character放在他们后面
	if( -1<firstsibling){	// the parent has child   string_code下还有其他节点,找到当前的最后一个节点
		nextsibling = firstsibling;   // 从第一个结点开始,找它的邻居
		while( -1<dictionary[nextsibling].nextsibling )   // 一直找到最后一个邻居
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值