Bmp图像的哈夫曼编码代码.doc
文本预览下载声明
Bmp图像的哈夫曼编码代码
#include stdio.h
#include stdlib.h
#include string.h
#include math.h
#include windows.h
#include ctype.h
#include malloc.h
typedef struct{
unsigned int weight;
unsigned int parent,lchild,rchild;
}HTNode, *huffmantree;// 动态分配数组存储赫夫曼树
typedef char **huffmancode;// 动态分配数组存储赫夫曼编码表
int power(int i)
{
int j,result=1;
for(j=0;ji;j++)
{
result*=2;
}
return result;
}
void write_file(char temp[],FILE *fp2)
{
int i;
unsigned char result=0;
for(i=8;i0;i--)
{
if(temp[8-i]!=0)
{
result+=power(i-1);
}
}
strcpy(temp,temp+8);
}
void select(huffmantree HT, unsigned int i, unsigned int *s1, unsigned int *s2)
{// s1为最小的两个值中序号小的那个
unsigned int j,temp;
for(j=1;j=i;j++)
{
if(HT[j].parent==0)
{
*s2=j;
break;
}
}
for(;j=i;j++)
{
if(HT[j].parent==0 j!=*s2)
{
*s1=j;
break;
}
}
for(j=1;j=i;j++)
{
if(HT[j].parent==0 HT[j].weight HT[*s1].weight *s2!=j)
{
*s1=j;
}
}
for(j=1;j=i;j++)
{
if(HT[j].parent==0 HT[j].weight HT[*s2].weight *s1!=j)
{
*s2=j;
}
}
if(*s1*s2)
{
temp=*s1;
*s1=*s2;
*s2=temp;
}
}
void huffmancoding(huffmantree HT, huffmancode HC,unsigned long int *w, unsigned int n)
{
// w存放n个字符的权值(均0),构造赫夫曼树HT,并求出n个字符的赫夫曼编码HC
unsigned int s1,s2,start,c,f,i,m;// 0号单元未用
huffmantree p;
char *cd;
if (n=1)
{
return;
}
m=2*n-1;
HT=(huffmantree)malloc((m+1)*sizeof(HTNode));//malloc 向系统申请分配指定size个字节的内存空间。
for(p=HT+1,i=1; i=n; ++i,++p,++w)
{
p-weight=*w;
p-parent=0;
p-lchild=0;
p-rchild=0;
}
for(; i=m; ++i,++p)
{
p-weight=0;
p-parent=0;
p-lchild=0;
p-rchild=0;
}
for(i=n+1; i=m; ++i)// 建赫夫曼树
{ // 在HT[1~i-1]中选择parent为0且weight最小的两个结点,其序号分别为s1和s2
select(HT,i-1,s1,s2);
HT[s1].parent=i; HT[s2].parent=i;
HT[i].lchild=s1; HT[i].rchild=s2;
HT[i].weight=HT[s1].weight+HT[s2].weight;
}
// 从叶子到根逆向求每个字符的赫夫曼编码
HC=(huffmancode)malloc((n+1)*sizeof(char *));// 分配n个字符编码的头指针向量([0]不用
cd=(char *)malloc(n*sizeof(char));
cd[n-1]=\0;// 编码结束符
for(i=1; i=n; ++i)
{/
显示全部