LZW encoding implements compression by creating a string table that represents a longer string with shorter code. LZW compression algorithm is Unisys's patent, valid until 2003, so most of the relevant algorithms have also expired.
This code only completes the LZW encoding and decoding algorithm function, relatively simple (CAI) single (BI) in comparison to many code found on the net, understand the struct && recursive can be considered as the advantage.
#include <stdio.h> #include <algorithm> #include <math.h> #include <iostream> #include < Stdlib.h> #include <string.h>using namespace std;struct node{int pre;//prefix word corresponding code character char c;//current character}kda[65535];int Cnt,p,q;char w,v;void Init () {////First 256 dictionaries are generated by the corresponding ASCII code for (int i = 0;i < n; i + +) {kda[i].pre =-1; KDA[I].C = i;} CNT = 256; P =-1;} void out (int x) {/////Recursive output code word corresponds to Word, first save used to build dictionary if (kda[x].pre! =-1) {out (kda[x].pre); } else {V = kda[x].c; } printf ("%c", kda[x].c);} void Search () {int flag = 0;for (int i = 0;i < Cnt;i + +) {if (Kda[i].pre = = = P && kda[i].c = W) {//dictionary already exists update prefix corresponding code Word p = I;flag = 1; }}if (!flag) {//does not exist expand the dictionary, the output prefix corresponds to the code word and updates the prefix word kda[cnt].pre = P; KDA[CNT].C = W; printf ("%03x", P); P = (int) W; CNT + +; }}void () {out (Q); if (P! =-1) {//If the previous digit is not empty, the previous word is prefixed with the first digit of the word as a new word added to the dictionary kda[cnt].pre = P; KDA[CNT]. C = V; CNT + +; }}void Compress () {<span style= "white-space:pre" ></span>//encoding process init (); Freopen ("LZWin.txt", "R", stdin); Freopen ("LZWch.txt", "w", stdout), while ((w = GetChar ()) && W! = EOF) {Search ();} printf ("%03x\n", P);} void Decompress () {<span style= "White-space:pre" ></span>//decoding process Init (); Freopen ("LZWch.txt", "R", stdin), Freopen ("LZWout.txt", "w", stdout), while (scanf ("%03x", &q)! = EOF) {the ();}} int main () {Compress (); Decompress (); return 0;}
"Hand-punched" LZW-coded C + + implementation