Huffman compression and decompression Java implementation

Source: Internet
Author: User

Attach the complete code

http://download.csdn.net/download/u010485034/7847447

The principle of Huffman coding here is not to say, is. Here's a detailed implementation of compression and decompression using Huffman encoding.

This project uses Java implementations.


Coding

1. Flowchart


2. Data structure

Characterweight: Record the character value and its weight in the file to be compressed.

Class{char c;//character value int weight;  Weights string Code in the file;  Its corresponding Huffman encoding}

The node information in the Huffmannode:huffman tree.

Class{int parent;  parent node int lchild; Left son int rchild;  Right son int weight; Weight

3. Program Key points

Construction of 3.1 Huffman tree

Huffman tree variable:arraylist

To create a flowchart:

for (int i=0;i<list.size () -1;i++) {//w1:the First min weight w2:the second min weight//i1:the first min weight Inde X, i2:the second min weight indexint w1 = Max_value, w2=max_value; int i1 = 0, i2 = 0;//Find the both node with the minimum weightfor (int j=0;j<tree.size (); j + +) {huffmannode node = tree.g ET (j); if (Node.getweight () < W1 && node.getparent () ==-1) {W2 = W1;w1 = Node.getweight (); i2 = I1;i1 = j;} else if (node.getweight () <w2 && node.getparent () ==-1) {w2 = Node.getweight (); i2 = j;}} Set the both node to is the children of a new node, and add the new node to the Treehuffmannode Pnode = new Huffmannode (w 1+W2);p node.setlchild (i1);p node.setrchild (I2); Tree.add (Pnode); Tree.get (I1). SetParent (Tree.indexof (Pnode)); Tree.get (I2). SetParent (Tree.indexof (Pnode));}

3.2 Obtaining Huffman codes based on Huffman tree

The Huffman tree is traversed online from the leaf node. Until the root node is reached. Determines whether this bit value is 0 or 1, depending on whether the current node is the left son or the right son of its parent node.

Finally, the 0,1 string inversion obtained in turn obtains the Huffman encoding.

Code:

for (int i=0;i<list.size (); i++) {Huffmannode node = tree.get (i); Huffmannode Pnode = Tree.get (Node.getparent ()); String code = ""; while (true) {if (Pnode.getlchild () ==tree.indexof (node)) {code = "0" +code;} else if (pnode.getrchild () = = tree.indexof (node)) {code = "1" +code;} else {System.out.println ("Tree Node Error!!!"); return null;} Node=pnode;if (Node.getparent ()!=-1) Pnode=tree.get (Node.getparent ()); else break;} List.get (i). Setcode (new String);}
3.3 File Header design

Total characters

Int Four bytes

Number of character types

Short two bytes

Leaf node

Char character short parent node 3 bytes

Non-leaf node

Short left son short right son short parent node 6 bytes

File header Length (in bytes)

L= 9n

where n is the number of character types.

3.4 Encoding and writing of file contents

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmdq4ntazna==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

while ((Temp=reader.read ())!=-1) {//!= eof//get the code from the code tablestring Code = Codetable.get ((char) temp); c++;if (C>=COUNT/96) {System.out.print ("="); c=0;} Try{stringbuilder codestring = new StringBuilder (code); Outputstringbuffer.append (codestring); while ( Outputstringbuffer.length () >8) {Out.write (Short.parseshort (outputstringbuffer.substring (0, 8), 2); O Utputstringbuffer.delete (0, 8);}} catch (Exception e) {e.printstacktrace ();}}

decoding

1. Flowchart

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmdq4ntazna==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

2. Data structure

The node information in the Huffmannode:huffman tree.

class{

INT parent; Parent node

Int Lchild; Left son

Int Rchild; Right son

Int weight; Weight

Char C; The corresponding character value


3. Program Key points

3.1 Rebuilding the Huffman tree. The Huffman tree is originally stored in the file header, so it is simpler to reconstruct the Huffman tree.

Code:

in = new DataInputStream (new FileInputStream); count = In.readint (); charNum = In.readshort (); nodenum = 2*charnum-1; Rebuild the Huffman treefor (int i=0;i<charnum;i++) {huffmannode node = new Huffmannode ((char) in.readbyte ()); int Parent = In.readshort (); node.setparent (parent); Tree.add (node);} for (int i=charnum;i<nodenum;i++) {huffmannode node = new Huffmannode ("); int l = In.readshort (); int r = In.readshort (); int p = in.readshort (); Node.setlchild (L); Node.setrchild (R); node.setparent (P); Tree.add (node);}

3.2 Decoding

Decoding flowchart

while (true) {while (Buff.length () <32) {temp = In.readint (); String codestring = integer.tobinarystring (temp); while (Codestring.length () <32) {codestring= ' 0 ' +codestring;} Buff.append (codestring);} node = Tree.get (Tree.size ()-1);d EP = 0;while (! Node.getlchild () ==-1&&node.getrchild () ==-1)) {if (Dep>=buff.length ()) {System.out.println ("Buff Overflow ");} if (Buff.charat (dep) = = ' 0 ') {node = Tree.get (Node.getlchild ());} else if (Buff.charat (dep) = = ' 1 ') {node = Tree.get (Node.getrchild ());} ELSE{SYSTEM.OUT.PRINTLN ("Coding error");} dep++;} char C = node.getch (); num++;if (num>=n/99) {System.out.print ("="); num=0;} Count++;if (count>=n) {break;} Charbuff+=c;if (Charbuff.length () >256) {writer.write (charbuff); charbuff= "";} Buff.delete (0, DEP);}} catch (Eofexception e) {//just do Nothing}catch (Exception e) {e.printstacktrace ();} Finally{//there is data released in The buff and charbuff, so we need to process Themwhile (Buff.length () >0) {node = Tree.get (Tree.size ()-1);d EP = 0;while (!) Node.getlchild () ==-1&&node.getrchild () ==-1) {if (Dep>=buff.length ()) {break;} if (Buff.charat (dep) = = ' 0 ') {node = Tree.get (Node.getlchild ());} else if (Buff.charat (dep) = = ' 1 ') {node = Tree.get (Node.getrchild ());} ELSE{SYSTEM.OUT.PRINTLN ("Coding error");//return;} dep++;} char C = node.getch (); num++;if (num>=n/99) {System.out.print ("="); num=0;} Count++;if (count>=n) {break;} Charbuff+=c;if (Charbuff.length () >256) {try {writer.write (charbuff);} catch (IOException E1) {//TODO auto-generated Catch Blocke1.printstacktrace ();} Charbuff= "";} Buff.delete (0, DEP);} try {writer.write (charbuff); Writer.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} }try{writer.close ();} catch (IOException e) {throw e;}

Finish project is not published and updated later.

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Huffman compression and decompression Java implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.