LZW编解码

LZW压缩算法解析

LZW简介

Lempel-Ziv-Welch Encoding ,简称 LZW 的压缩算法。LZW压缩算法的基本原理:提取原始文本文件数据中的不同字符,基于这些字符创建一个编译表,然后用编译表中的字符的索引来替代原始文本文件数据中的相应字符,减少原始数据大小。字符串和编码的对应关系是在压缩过程中动态生成的,并且隐含在压缩数据中,解压的时候根据表来进行恢复,算是一种无损压缩

LZW编码流程

LZW解码流程

数据结构分析

字典树

struct {                                       //定义词典的结构
	int suffix;                            //尾缀字符
	int parent, firstchild, nextsibling;   //母节点,第一个孩子节点,下一个兄弟节点
} dictionary[MAX_CODE+1];

 

主要功能模块

void InitDictionary( void){                       //初始化字典,即将256个字符及其对应编码(0-255)输入到字典
	int i;

	for( i=0; i<256; i++){
		dictionary[i].suffix = i;
		dictionary[i].parent = -1;       
		dictionary[i].firstchild = -1;
		dictionary[i].nextsibling = i+1; //后一个就是当前节点的兄弟节点
	}
	dictionary[255].nextsibling = -1;        //最后一个没有兄弟节点
	next_code = 256;                         //下一个suffix是256
}
/*
 * Input: string represented by string_code in dictionary,
 * Output: the index of character+string in the dictionary
 * 		index = -1 if not found
 */
int InDictionary( int character, int string_code){                 //查找词典中是否有字符串
	int sibling;                                               
	if( 0>string_code) return character;                       //如果前面无前缀,返回当前字符   
	sibling = dictionary[string_code].firstchild;              //前缀为string_code的第一个孩子节点
	while( -1<sibling){        
		if( character == dictionary[sibling].suffix) return sibling; //如果当前child的尾缀和字符character相同,返回srting+character
		sibling = dictionary[sibling].nextsibling;                   //否则查找当前child的下一个兄弟节点
	}
	return -1;
}

 

void AddToDictionary( int character, int string_code){      //将新串加入字典
	int firstsibling, nextsibling;
	if( 0>string_code) return;
	dictionary[next_code].suffix = character;
	dictionary[next_code].parent = string_code;
	dictionary[next_code].nextsibling = -1;
	dictionary[next_code].firstchild = -1;
	firstsibling = dictionary[string_code].firstchild;
	if( -1<firstsibling){	                                      // the parent has child
		nextsibling = firstsibling;
		while( -1<dictionary[nextsibling].nextsibling ) 
			nextsibling = dictionary[nextsibling].nextsibling;
		dictionary[nextsibling].nextsibling = next_code;
	}else{                                                        // no child before, modify it to be the first
		dictionary[string_code].firstchild = next_code;
	}
	next_code ++;
}

主要代码

main函数 

int main( int argc, char **argv){
	FILE *fp;                      //输入的文件
	BITFILE *bf;                   //输出的文件

	//调试需要4个输入参数,分别是argv[0]:提示使用方法(编解码标识
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值