霍夫曼編碼和解碼

2021-07-11 03:15:41 字數 2524 閱讀 9885

編碼步驟:

1、準備待編碼的字串(可以從文字檔案中讀取不包含中文)。

2、統計字串中每個字元出現的次數。(設定乙個長度為256的陣列,使用字元對應的ascii碼作為陣列下標,儲存次數。如:array[『a』]=10;表示字元a出現10次。)

3、根據上面的陣列,生成節點。(每個字元對應乙個節點,以鍊錶形式鏈結起來,同時鍊錶按從小到大排序。)

4、構造霍夫曼樹。每次刪除鍊錶中的兩個節點,生成乙個新節點。並將這個節點重新插入到鍊錶合適位置。(構造霍夫曼樹參考:開啟)。霍夫曼樹解碼時需要使用。

5、通過前序遍歷,求出每個字元的二進位制編碼。同樣設定乙個長度為256的陣列,下標為字元對應的ascii碼。沒出現的字元編碼為null,不考慮。

6、根據求出的二進位制編碼替換原來的每個字元。得到整個字串對應的二進位制編碼。

7、將二進位制編碼按照每8位生成乙個新字元。最後剩的不足8位的在後面補上count個0,計算乙個新字元。補0的個數解碼時需要使用。

8、將這些生成的新字元替換掉二進位制編碼字串,即可得到編碼後的內容。長度將在一定程度上變短。

public

class

node

}

public

class

huffmancode

// 對任意字串進行霍夫曼編碼

public

static string code(string str)

int len = str.length();

char c;

for(i=0; i// 求次數

c = str.charat(i);

n[c]++;

}// 構造乙個單向鍊錶,從小到大順序排列森林中的樹

node t, p, pp;

for(i=0; i<256; i++) else else else

}// 在結尾插入

if(p == null && pp != null) }}

}}

// 根據這個單向鍊錶森林,構造霍夫曼樹

node min1, min2;

node newnode;

while(head.next != null) else else else

}// 在結尾插入

if(p == null && pp != null) }}

}// 霍夫曼樹構造完畢,求出對應編碼,head為樹根節點

string bianma = new string[256];

for(i=0; i<256; i++)

preorder(head, bianma, "");

// 使用編碼替換原來的文字

string result = "";

for(i=0; i// 將編碼每8位轉化成乙個ascii碼字元

string s;

int m = 1;

int j;

int r;

string real = "";

while(result.length() >= 8)

real += (char)r;

}count = 8 - result.length(); // 補0的個數

for(j=0; j'0';

}r = 0;

m = 1;

for(j=7; j>=0; j--)

real += (char)r;

return real;

}public

static

void

preorder(node head, string bianma, string str)

str += "0";

preorder(head.lchild, bianma, str);

str = str.substring(0, str.length() - 1);

str += "1";

preorder(head.rchild, bianma, str);

str = str.substring(0, str.length() - 1);

}// 根據霍夫曼樹對給定字串解碼

public

static string decode(string str)

while(b.length() < 8)

result += b; // 原來的二進位制串

}int len = result.length()-count; // 真實二進位制字串長度需要去除補得0

string real = "";

node p = head;

for(int i=0; iif(p.data == 256) else

if(p.data != 256) }}

return real;

}}

注意:本**對ascii碼內字元適用。因為其他字元(無論採用哪種編碼)超過乙個位元組,計數和統計編碼的陣列下標將越界。

資料結構與演算法 霍夫曼樹 霍夫曼編碼和解碼

找出存放一串字元所需的最少的二進位制編碼。首先統計出每種字元出現的頻率,即 概率 權值。例如 頻率表 a 60,b 45,c 13 d 69 e 14 f 5 g 3 第一步 找出字元中頻率最小的兩個,小的在左邊,大的在右邊,組成二叉樹。在頻率表中刪除此次找到的兩個數,並加入此次最小兩個數的頻率和。...

編譯碼 霍夫曼編譯碼

1.檔案源 原始影象分塊為 8 8 在rle編碼之後做霍夫曼編碼。其中rle碼字格式如下。struct rlecode 2.構建霍夫曼表 本文中使用的為jpeg標準ac y霍夫曼表。構建乙個256維大小的碼表hufftable,其霍夫曼碼字結構如下。struct huffcode 3.關鍵幀霍夫曼編...

霍夫曼編碼

一 八卦 在 演算法為什麼這麼難?這篇部落格裡,劉未鵬講了乙個八卦 根據wikipedia的介紹,霍夫曼同學 當年還在讀ph.d,所以的確是 同學 而這個問題是坑爹的導師robert m.fano 給他們作為大作業的 fano自己和shannon合作給出了乙個suboptimal的編碼方案,為得不到...