【手打】LZW编码的C/C++实现
2016-01-27 20:56
621 查看
LZW编码通过建立一个字符串表,用较短的代码来表示较长的字符串来实现压缩。 LZW压缩算法是Unisys的专利,有效期到2003年,所以相关算法大多也已过期。
本代码只完毕了LZW的编码与解码算法功能,相对网上找到的非常多代码而言较为简(cai)单(bi)。了解struct && 会递归就可以,算是长处吧。
本代码只完毕了LZW的编码与解码算法功能,相对网上找到的非常多代码而言较为简(cai)单(bi)。了解struct && 会递归就可以,算是长处吧。
#include <stdio.h> #include <algorithm> #include <math.h> #include <iostream> #include <stdlib.h> #include <string.h> using namespace std; struct Node{ int pre; //前缀单词相应码字 char c; //当前字符 }KDA[65535]; int cnt,P,Q; char W,V; void Init(){ //前256个字典由相应ASCII码生成 for(int i = 0;i < 256; i ++){ KDA[i].pre = -1; KDA[i].c = i; } cnt = 256; P = -1; } void Out(int x){ //递归输出码字相应单词,首位另存用于建立字典 if(KDA[x].pre != -1){ Out(KDA[x].pre); } else { V = KDA[x].c; } printf("%c",KDA[x].c); } void Search(){ int flag = 0; for(int i = 0;i < cnt;i ++){ if(KDA[i].pre == P && KDA[i].c == W){//字典已存在则更新前缀相应码字 P = i; flag = 1; } } if(!flag){ //不存在则扩充字典,输出前缀相应码字并更新前缀单词 KDA[cnt].pre = P; KDA[cnt].c = W; printf("%03X ",P); P = (int)W; cnt ++; } } void Research(){ Out(Q); if(P != -1){ //假设前一位码字不为空,则将前一位相应单词作为前缀与本单词第一位合并作为新单词增加字典 KDA[cnt].pre = P; KDA[cnt].c = V; cnt ++; } } void Compress(){<span style="white-space:pre"> </span>//编码过程 Init(); freopen("LZWin.txt","r",stdin); freopen("LZWch.txt","w",stdout); while((W = getchar()) && W != EOF){ Search(); } printf("%03X\n",P); } void Decompress(){<span style="white-space:pre"> </span>//解码过程 Init(); freopen("LZWch.txt","r",stdin); freopen("LZWout.txt","w",stdout); while(scanf("%03X",&Q)!= EOF){ Research(); } } int main(){ Compress(); Decompress(); return 0; }
相关文章推荐
- 英语数字转换器
- C++文件读写
- 小蚂蚁学习C语言(36)——题目——字符串的倒置
- UTF-8, Unicode, GB2312格式串转换之C语言版
- [土狗之路]coursera上C语言进阶第二周作业
- 类和对象—复数类
- C++ 类模板
- 快速排序算法的实现
- C++小实验:在C++中实现类似于动态语言函数定义的宏
- C语言-----算法
- 20160126.CCPP体系详解(0005天)
- C++项目文件中的后缀名为SDF的文件是什么?有什么用?
- effective C++ 笔记二
- C++:wchar_t 和C++新增类型:char16_t char32_t
- using c++11 standerd in qt
- C语言学习笔记 逻辑结构关键字
- How to learn C++ and find all STL Algorithm reference
- ubuntu使用技巧——如何编译C++和C语言的使用程序
- C++ map 和 multimap
- PAT_乙级1001