Huffman樹在實際文章壓縮中的應用

2021-10-10 18:15:45 字數 3409 閱讀 4505

huffman樹的儲存結構在電腦記憶體中的實現:

typedef

struct hnodehnode;

通過乙個結構體陣列來儲存huffman樹,其中陣列元素即是乙個結點,內儲存了該結點所代表的英文本元,在文章中的權值,其父親以及左孩子和右孩子的下標,當沒有孩子或者父親的時候,該值置-1。

下面**可以從檔案中讀入字元並儲存在letter[maxlength]中,並統計得到每個字元的權值:

int

readfile

(char

*letter)

while(!

feof

(fp)

)return i;

}int

calculate

(char

*letter,hnode *weight_table,

int total_letter)}if

(flag==0)

flag=0;

}return(2

*n-1);

//返回值為建立huffman結構體陣列的大小

}

從權值表weight_table中取出兩個最小的權值之和作為他們的父親,直到只有乙個元素未被取出為止:

void

getleast

(hnode *weight_table,

int n,

int*index1,

int*index2)

} weight_table[

*index1]

.parent=0;

//暫時置0

for(i=

0;iweight_table[

*index1]

.parent=-1

;//恢復

}void

createhtree

(hnode *weight_table,

int scale_table)

}

話不多說,下面直接上全部**,一下**能夠讀入txt檔案中的英文本元,生成每個字元的huffman編碼,並計算得到壓縮率,並能夠輸出文章壓縮後的01序列,最後可以根據01序列還原得到原文章:

#include

#include

#include

#include

#define maxlength 100000

#define maxium 1000

file *fp,

*fp1,

*fp2;

typedef

struct hnodehnode;

typedef

struct stackstack;

typedef

struct codecode;

void

inithtree

(hnode *weight_table)

}int

readfile

(char

*letter)

while(!

feof

(fp)

)return i;

}int

calculate

(char

*letter,hnode *weight_table,

int total_letter)}if

(flag==0)

flag=0;

}return(2

*n-1);

}void

getleast

(hnode *weight_table,

int n,

int*index1,

int*index2)

} weight_table[

*index1]

.parent=0;

//暫時置0

for(i=

0;iweight_table[

*index1]

.parent=-1

;//恢復

}void

createhtree

(hnode *weight_table,

int scale_table)

}void

pushstack

(stack *temp,

int mark)

intpopstack

(stack *temp)

void

enqueue

(code *coding,

int mark)

//輸出壓縮後的01序列

void

printcoding

(hnode *weight_table,code *htreecoding,

int scale_table,

char

*letter,

int total_letter)

for(i=

0;i)break;}

}}}void

printdecoding

(hnode *weight_table,

int scale_table)if(

(fp2=

fopen

("test_decoding.txt"

,"w"))

==null

)//找最先父親

for(i=

0;i(weight_table[i]

.parent==-1

) temp=index_ancestor;

while(!

feof

(fp1))}

}main()

//壓棧,獲得字元逆編碼

while

(temp.top!=0)

//彈棧,獲得字元編碼

printf

("\n");

}for

(i=0

;i<

(scale_table+1)

/2;i++

) now_bits=now_bits+weight_table[i]

.weight*htreecoding[i]

.total_bits;

printf

("\n哈夫曼樹的壓縮率是: %f"

,now_bits/

(total_letter*8)

);//建立哈夫曼樹的過程

//解碼加輸出01序列的過程

printcoding

(weight_table,htreecoding,scale_table,letter,total_letter)

;//輸出01序列

printdecoding

(weight_table,scale_table)

;}

利用Huffman樹實現檔案壓縮

利用huffman樹實現檔案壓縮 使用的編輯語言是c 專案目的是能夠實現對檔案的壓縮及解壓,涉及到的技術主要有huffman樹的實現,檔案的io操作,優先順序佇列等 整體思路 整個過程是依賴於huffman樹,因此要構建出乙個可供我們使用的huffman樹 壓縮時,操作原始檔,以字元形式讀取檔案資訊...

正規化Huffman樹在檔案壓縮專案中的應用

正規化huffman樹不用建立,可以利用huffman樹推到出來 壓縮 通過huffman碼表推算出每個字元的正規化huffman編碼 讀取原始檔,將原始檔中的每個位元組按照對應的正規化huffman編碼進行改寫 壓縮檔案的格式 解壓縮 從壓縮資料中獲取符號的編碼位長,構建符號位長表 根據編碼位長建...

利用huffman樹實現字元文件的壓縮

huffman樹壓縮字元文件,就是將8bit的字元根據出現頻率進行重新編碼,使編碼之後每個字元的編碼在檔案讀入時都能被唯一確定。故字元的編碼必須是不頭包含的。huffman樹是一種簡單的壓縮編碼方式。本文將採用c語言實現。編譯環境為gcc4.9.2,故可以採用c 的引用傳遞使 更加簡單。首先,先編乙...