欢迎来到天天文库
浏览记录
ID:62659661
大小:15.89 KB
页数:9页
时间:2021-05-15
《霍夫曼编码对英文文本的压缩和解压缩.docx》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Huffman编码对英文文本的压缩和解压缩中国地质大学计算机学院信息安全专业信息论实验报告#include#include#include//记录字符在数组中的位置//字符出现频率(权值)//定义哈夫曼树指针变量//定义存储哈夫曼编码的数组structhead{unsignedcharb;longcount;longparent,lch,rch;charbits[256];}header[512],tmp;voidcompress(){char[255],outp
2、ut],buf[512];unsignedcharc;longn,m,i,j,f;//作计数或暂时存储数据用longmin1,pt1,flength=0,length1,length2;//记录最小结点、文件长度doublediv;//计算压缩比用FILE*ifp,*ofp;//分别为输入、输出文件指针printf("t请您输入需要压缩的文件(需要路径):");gets();ifp=fopen(,"rb");if(ifp==NULL){printf("t文件打开失败!");system("pause");r
3、eturn;}printf("t请您输入压缩后的文件名(如无路径则默认为桌面文件):");gets(outputfile);ofp=fopen(outputfile,"wb");if(ofp==NULL){printf("t压缩文件失败!");system("pause");return;}flength=0;while(!feof(ifp)){fread(&c,1,1,ifp);header[c].count++;//字符重复出现频率+1flength++;//字符出现原文件长度+1}flength--;
4、length1=flength;//原文件长度用作求压缩率的分母header[c].count--;for(i=0;i<512;i++){if(header[i].count!=0)header[i].b=(unsignedchar)i;/*将每个哈夫曼码值及其对应的ASCII码存放在一维数组header[i]中,且编码表中的下标和ASCII码满足顺序存放关系*/elseheader[i].b=0;header[i].parent=-1;header[i].lch=header[i].rch=-1;//对结点进行初始化
5、}for(i=0;i<256;i++){//按出现权值从大到小排序for(j=i+1;j<256;j++){if(header[i].count6、现的最大次数for(j=0;jheader[j].count){pt1=j;min1=header[j].count;continue;}}header[i].count=header[pt1].count;header[pt1].parent=i;header[i].lch=pt1;min1=999999999;for(j=0;j7、{if(header[j].parent!=-1)continue;if(min1>header[j].count){pt1=j;min1=header[j].count;continue;}}header[i].count+=header[pt1].count;header[i].rch=pt1;header[pt1].parent=i;//哈夫曼无重复前缀编码}for(i=0;i8、=f;f=header[f].parent;if(header[f].lch==j){//置左分支编码0j=strlen(header[i].bits);memmove(header[i].bits+1,header[i].bits,j+1);//依次存储连接"0""1"编码,此处语句为网络借鉴header[i].bits[0]=
6、现的最大次数for(j=0;jheader[j].count){pt1=j;min1=header[j].count;continue;}}header[i].count=header[pt1].count;header[pt1].parent=i;header[i].lch=pt1;min1=999999999;for(j=0;j
7、{if(header[j].parent!=-1)continue;if(min1>header[j].count){pt1=j;min1=header[j].count;continue;}}header[i].count+=header[pt1].count;header[i].rch=pt1;header[pt1].parent=i;//哈夫曼无重复前缀编码}for(i=0;i8、=f;f=header[f].parent;if(header[f].lch==j){//置左分支编码0j=strlen(header[i].bits);memmove(header[i].bits+1,header[i].bits,j+1);//依次存储连接"0""1"编码,此处语句为网络借鉴header[i].bits[0]=
8、=f;f=header[f].parent;if(header[f].lch==j){//置左分支编码0j=strlen(header[i].bits);memmove(header[i].bits+1,header[i].bits,j+1);//依次存储连接"0""1"编码,此处语句为网络借鉴header[i].bits[0]=
此文档下载收益归作者所有