Today's curriculum design is finally finished, has done nearly a week of Huffman also temporarily over. During the period of compression, but also opened up the vision, and know a head file <bitset> Then we'll summarize the compression method used.
Compression:
while (Str.size () >= 8) { string str2 (str, 0, 8); Read the top 8 bitset<8> foo (str2) from Str; Intercepts the first 8 bits char bigch = (char) foo.to_ulong (); Convert foo to unsigned long unsigned, still using Foo's 8-bit storage, and then convert the unsigned long integer strong to a char character myfile << bigch; Write in binary to file str.erase (0, 8); Remove the first 8 characters from the original string }
We're not going to be so lucky when we compress. Just 8 bits, we need to deal with, judge the last remaining str.size () size, int nn = 8-str.size (), this is not enough 8 bits of us in the code finally directly fill ' 0 ', gather enough 8 bits, Then the NN also saved to the end of the file, in the decompression when the NN read out, and then the last all the code after the decompression to remove their own added nn ' 0 ', so that the code is the real code.
The above program is equivalent to compressing 8 bits into a char, thus achieving the purpose of compression.
Extract:
Ifstream ffile ("Final.txt", ios_base::binary); Binary Open compressed file string foo, fstr = ""; int a[8]; FFILE.SEEKG ( -1l, ios::end); Goto the file end //navigates to the last character of the document, reading the nn char cc; Ffile.get (cc); int xx = cc-' 0 '; Get the number of extra charactor//turn into digital ffile.seekg (0L, Ios::beg); Goto file begin //Navigate to the beginning of the document to read the compressed character while (Getline (Ffile, foo)) { int len = Foo.size (); for (int i=0; i<len; i++) { bitset<8> fx (Foo[i]); Extract a character into the array fx for (int j=7; j>=0; j--) Fstr + = (fx[j] + ' 0 '); Note is reversed } } fstr.erase (Fstr.size ()-8-xx, 8 + xx); Add yourself xx ' 0 ' to remove ffile.close (); Close File
So we get the 01 coded string before the compression fstr~~~
The above is in the writing course design to learn the compression has been decompression method, relatively superficial, later know more, and then to update ^_^
Compression and decompression of Huffman coding compression algorithm