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]:提示使用方法(编解码标识
LZW压缩算法解析

最低0.47元/天 解锁文章
3002

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



