欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LZW编码算法实现与分析

程序员文章站 2022-07-14 22:03:56
...

编码原理

不断地从字符流中提取新定字符串,然后用码字表示这个字符串。从而对字符流的编码转换为对字符流对应码字的编码,达到数据压缩的目的。

数据结构分析:

尾缀字符(suffix)
母节点(parent)
第一个孩子节点(firstchild)
下一个兄弟节点(nextsibling)

编码算法步骤:1.将词典初始化为包含所有可能的字符,当前前缀P初始化为空

​ 2.令当前字符C=字符流中的下一字符

​ 3.判断P+C是否在词典中

​ (1)若是,则P=P+C,回到步骤二

​ (2)若否,输出与当前前缀P相对应的码字W,将P+C添加到词典中,令P=C,返回步骤2

解码步骤:1.在开始译码时,词典包含所有可能的前缀根

​ 2.令CW=码流中第一个码字

​ 3.输出当前前缀字符串string.CW到字符流

​ 4.先前码字PW=当前码字CW

			   5.当前码字CW=码字流的下一个码字

​ 6.判断当前前缀字符串string.CW是否在词典中

​ (1)若是,将当前前缀字符串string.CW输出到字符流,当前前缀P=先前前缀字符串string.PW,当前字符C=当前前缀字符串string.CW的第一个字符

​ (2)若否,则当前前缀P=先前前缀字符串string.PW。当前字符C=当前前缀字符串string.CW的第一个字符。输出前缀字符串P+C到字符流,然后把它添加到词典中。

​ 7.判断码字流中是否还有码字要译。

​ (1)如果”是”,就返回步骤4。

​ (2)如果”否”,结束。

!!当解码时string.CW字符串不在词典中

为什么string.CW在词典中找不到?

原因:该字符串被写入词典后立刻就被输出了。因为解码时词典是先出现字符串再写入词典中,编码是先写入到词典中再进行输出。所以若该字符串在编码时,被写入词典后立刻就输出了,则在解码时我们会先看到输出的码字但是在词典中找不到对应字符。下面用例子举例说明更清楚

eg1.字符串:abcabababc

编码:

P C P+C 词典 输出
0 a a a=1 ;b=2;c=3
a b ab a=1;b=2;c=3;ab=4 1
b c bc a=1;b=2;c=3;ab=4;bc=5 12
c a ca a=1;b=2;c=3;ab=4;bc=5;ca=6 123
a b ab a=1;b=2;c=3;ab=4;bc=5;ca=6 123
ab a aba a=1;b=2;c=3;ab=4;bc=5;ca=6;aba=7 1234
a b ab a=1;b=2;c=3;ab=4;bc=5;ca=6;aba=7 1234
ab a aba a=1;b=2;c=3;ab=4;bc=5;ca=6;aba=7 1234
aba b abab a=1;b=2;c=3;ab=4;bc=5;ca=6;aba=7;abab=8 12347
b c bc a=1;b=2;c=3;ab=4;bc=5;ca=6;aba=7;abab=8 123475

解码:123475

PW CW P C P+C 词典 输出
1 a=1 ;b=2;c=3 a
1 2 a b ab a=1 ;b=2;c=3;ab=4 ab
2 3 b c bc a=1 ;b=2;c=3;ab=4;bc=5 abc
3 4 c a ca a=1 ;b=2;c=3;ab=4;bc=5;ca=6 abcab
4 7 ab a aba a=1 ;b=2;c=3;ab=4;bc=5;ca=6;aba=7 abcababa
7 5 aba b abab a=1 ;b=2;c=3;ab=4;bc=5;ca=6;aba=7;abab=8 abcabababc

eg2:abcababcba

编码

P C P+C 词典 输出
a a a=1 ;b=2;c=3
a b ab a=1;b=2;c=3;ab=4 1
b c bc a=1;b=2;c=3;ab=4;bc=5 12
c a ca a=1;b=2;c=3;ab=4;bc=5;ca=6 123
a b ab a=1;b=2;c=3;ab=4;bc=5;ca=6 123
ab a aba a=1;b=2;c=3;ab=4;bc=5;ca=6;aba=7 1234
a b ab a=1;b=2;c=3;ab=4;bc=5;ca=6;aba=7 1234
ab a abc a=1;b=2;c=3;ab=4;bc=5;ca=6;abc=7 12344
c b cb a=1;b=2;c=3;ab=4;bc=5;ca=6;aba=7;cb=8 123443
b c bc a=1;b=2;c=3;ab=4;bc=5;ca=6;aba=7;cb=8 1234435

解码:1234435

PW CW P C P+C 词典 输出
1 a=1 ;b=2;c=3 a
1 2 a b ab a=1 ;b=2;c=3;ab=4 ab
2 3 b c bc a=1 ;b=2;c=3;ab=4;bc=5 abc
3 4 c a ca a=1 ;b=2;c=3;ab=4;bc=5;ca=6 abcab
4 4 ab a aba a=1 ;b=2;c=3;ab=4;bc=5;ca=6;aba=7 abcabab
4 3 ab c abc a=1 ;b=2;c=3;ab=4;bc=5;ca=6;aba=7;abc=8 abcababc
3 5 c b cb a=1 ;b=2;c=3;ab=4;bc=5;ca=6;aba=7;abc=8;cb=9 abcababcbc

上面两个例子对比,ababa会出现码字不在词典中的情况。假设P=ab,C=X;P+C=abX不在词典中,输出ab=4,将字符串abX写入词典abX=7;P=X,若下一个字符串立刻输出刚才写入的码字7,则P+C不在词典中,所以输出P=abX,又P一定为上一个字符的C即X开始,所以X=a。

P C P+C 词典 输出
ab X abX a=1;b=2;c=3;ab=4;bc=5;ca=6;abX=7 4
X Y XY XY存在在词典中 4
XY Z XYZ XYZ=7存在在词典中 4
XYZ W XYZW a=1;b=2;c=3;ab=4;bc=5;ca=6;abX=7;XYZW=8 7

所以XYZ=abX,解得:X=a,Y=b,Z=a。可以得出X实际为上一个输出码字的第一个字符即先前前缀字符串的第一个字符

PW CW P C P+C 词典 输出
3 4 c ab ca a=1 ;b=2;c=3;ab=4;bc=5;ca=6 ab
4 7 ab X abX a=1 ;b=2;c=3;ab=4;bc=5;ca=6;abX=7 ababX

对应到解码过程中,先前前缀字符串CW=当前前缀字符串PW,所以C=当前前缀字符串的第一个字符,即X=a。

代码:

/*
 * Declaration for bitwise IO
 *
 * vim: ts=4 sw=4 cindent
 */
#ifndef __BITIO__
#define __BITIO__

#include <stdio.h>

typedef struct{
	FILE *fp;
	unsigned char mask;
	int rack;
}BITFILE;

BITFILE *OpenBitFileInput( char *filename);//打开需要进行解码的文件
BITFILE *OpenBitFileOutput( char *filename);//打开需要输出的编码的文件
void CloseBitFileInput( BITFILE *bf);//关闭需要进行解码的文件
void CloseBitFileOutput( BITFILE *bf);//关闭输出的编码文件
int BitInput( BITFILE *bf);
unsigned long BitsInput( BITFILE *bf, int count);
void BitOutput( BITFILE *bf, int bit);
void BitsOutput( BITFILE *bf, unsigned long code, int count);
#endif	// __BITIO__

/*
 * Definitions for bitwise IO
 *
 * vim: ts=4 sw=4 cindent
 */

#include <stdlib.h>
#include <stdio.h>
#include "bitio.h"
#pragma warning(disable:4996);
BITFILE *OpenBitFileInput( char *filename){
	BITFILE *bf;
	bf = (BITFILE *)malloc( sizeof(BITFILE));
	if( NULL == bf) return NULL;
	if( NULL == filename)	bf->fp = stdin;
	else bf->fp = fopen( filename, "rb");
	if( NULL == bf->fp) return NULL;
	bf->mask = 0x80;
	bf->rack = 0;
	return bf;
}

BITFILE *OpenBitFileOutput( char *filename){
	BITFILE *bf;
	bf = (BITFILE *)malloc( sizeof(BITFILE));
	if( NULL == bf) return NULL;
	if( NULL == filename)	bf->fp = stdout;
	else bf->fp = fopen( filename, "wb");
	if( NULL == bf->fp) return NULL;
	bf->mask = 0x80;
	bf->rack = 0;
	return bf;
}

void CloseBitFileInput( BITFILE *bf){
	fclose( bf->fp);
	free( bf);
}

void CloseBitFileOutput( BITFILE *bf){
	// Output the remaining bits
	if( 0x80 != bf->mask) fputc( bf->rack, bf->fp);
	fclose( bf->fp);
	free( bf);
}

int BitInput( BITFILE *bf){
	int value;

	if( 0x80 == bf->mask){
		bf->rack = fgetc( bf->fp);
		if( EOF == bf->rack){
			fprintf(stderr, "Read after the end of file reached\n");
			exit( -1);
		}
	}
	value = bf->mask & bf->rack;
	bf->mask >>= 1;
	if( 0==bf->mask) bf->mask = 0x80;
	return( (0==value)?0:1);
}

unsigned long BitsInput( BITFILE *bf, int count){
	unsigned long mask;
	unsigned long value;
	mask = 1L << (count-1);
	value = 0L;
	while( 0!=mask){
		if( 1 == BitInput( bf))
			value |= mask;
		mask >>= 1;
	}
	return value;
}

void BitOutput( BITFILE *bf, int bit){
	if( 0 != bit) bf->rack |= bf->mask;
	bf->mask >>= 1;
	if( 0 == bf->mask){	// eight bits in rack
		fputc( bf->rack, bf->fp);
		bf->rack = 0;
		bf->mask = 0x80;
	}
}

void BitsOutput( BITFILE *bf, unsigned long code, int count){
	unsigned long mask;

	mask = 1L << (count-1);
	while( 0 != mask){
		BitOutput( bf, (int)(0==(code&mask)?0:1));
		mask >>= 1;
	}
}
#if 0
int main( int argc, char **argv){
	BITFILE *bfi, *bfo;
	int bit;
	int count = 0;

	if( 1<argc){
		if( NULL==OpenBitFileInput( bfi, argv[1])){
			fprintf( stderr, "fail open the file\n");
			return -1;
		}
	}else{
		if( NULL==OpenBitFileInput( bfi, NULL)){
			fprintf( stderr, "fail open stdin\n");
			return -2;
		}
	}
	if( 2<argc){
		if( NULL==OpenBitFileOutput( bfo, argv[2])){
			fprintf( stderr, "fail open file for output\n");
			return -3;
		}
	}else{
		if( NULL==OpenBitFileOutput( bfo, NULL)){
			fprintf( stderr, "fail open stdout\n");
			return -4;
		}
	}
	while( 1){
		bit = BitInput( bfi);
		fprintf( stderr, "%d", bit);
		count ++;
		if( 0==(count&7))fprintf( stderr, " ");
		BitOutput( bfo, bit);
	}
	return 0;
}
#endif

/*
 * Definition for LZW coding 
 *
 * vim: ts=4 sw=4 cindent nowrap
 */
#include <stdlib.h>
#include <stdio.h>
#include "bitio.h"
#define MAX_CODE 65535
#pragma warning(disable:4996);
struct {
	int suffix;
	int parent, firstchild, nextsibling;
} dictionary[MAX_CODE+1];
int next_code;
int d_stack[MAX_CODE]; // stack for decoding a phrase

#define input(f) ((int)BitsInput( f, 16))
#define output(f, x) BitsOutput( f, (unsigned long)(x), 16)

int DecodeString( int start, int code);
void InitDictionary( void);
void PrintDictionary( void){
	int n;
	int count;
	for( n=256; n<next_code; n++){
		count = DecodeString( 0, n);
		printf( "%4d->", n);
		while( 0<count--) printf("%c", (char)(d_stack[count]));
		printf( "\n");
	}
}

int DecodeString( int start, int code){
	int count;
	count = start;
	while( 0<=code){
		d_stack[ count] = dictionary[code].suffix;
		code = dictionary[code].parent;
		count ++;
	}
	return count;
}
void InitDictionary( void){
	int i;

	for( i=0; i<256; i++){
		dictionary[i].suffix = i;
		dictionary[i].parent = -1;
		dictionary[i].firstchild = -1;
		dictionary[i].nextsibling = i+1;
	}
	dictionary[255].nextsibling = -1;
	next_code = 256;
}
/*
 * Input: string represented by string_code in dictionary,
 * Output: the index of character+string in the dictionary
 * 		index = -1 if not found
 */
int InDictionary( int character, int string_code){
	int sibling;
	if( 0>string_code) return character;
	sibling = dictionary[string_code].firstchild;
	while( -1<sibling){
		if( character == dictionary[sibling].suffix) return sibling;
		sibling = dictionary[sibling].nextsibling;
	}
	return -1;
}

void AddToDictionary( int character, int string_code){
	int firstsibling, nextsibling;
	if( 0>string_code) return;
	dictionary[next_code].suffix = character;
	dictionary[next_code].parent = string_code;
	dictionary[next_code].nextsibling = -1;
	dictionary[next_code].firstchild = -1;
	firstsibling = dictionary[string_code].firstchild;
	if( -1<firstsibling){	// the parent has child
		nextsibling = firstsibling;
		while( -1<dictionary[nextsibling].nextsibling ) 
			nextsibling = dictionary[nextsibling].nextsibling;
		dictionary[nextsibling].nextsibling = next_code;
	}else{// no child before, modify it to be the first
		dictionary[string_code].firstchild = next_code;
	}
	next_code ++;
}

void LZWEncode( FILE *fp, BITFILE *bf){
	int character;
	int string_code;
	int index;
	unsigned long file_length;

	fseek( fp, 0, SEEK_END);
	file_length = ftell( fp);
	fseek( fp, 0, SEEK_SET);
	BitsOutput( bf, file_length, 4*8);
	InitDictionary();
	string_code = -1;
	while( EOF!=(character=fgetc( fp))){
		index = InDictionary( character, string_code);
		if( 0<=index){	// string+character in dictionary
			string_code = index;
		}else{	// string+character not in dictionary
			output( bf, string_code);
			if( MAX_CODE > next_code){	// free space in dictionary
				// add string+character to dictionary
				AddToDictionary( character, string_code);
			}
			string_code = character;
		}
	}
	output( bf, string_code);
}

void LZWDecode( BITFILE *bf, FILE *fp){
	int character;
	int new_code, last_code;
	int phrase_length;
	unsigned long file_length;

	file_length = BitsInput( bf, 4*8);
	if( -1 == file_length) file_length = 0;
	InitDictionary();
	last_code = -1;
	while (0 < file_length) {
		new_code = input(bf);
		if (new_code >= next_code) { // this is the case CSCSC( not in dict)
			d_stack[0] = character;
			phrase_length = DecodeString(1, last_code);
		}
		else {
			phrase_length = DecodeString(0, new_code);
		}
		character = d_stack[phrase_length - 1];
		while (0 < phrase_length) {
			phrase_length--;
			fputc(d_stack[phrase_length], fp);
			file_length--;
		}
		if (MAX_CODE > next_code) {	// add the new phrase to dictionary
			AddToDictionary(character, last_code);
		}
		last_code = new_code;
	}

}



int main( int argc, char **argv){
	FILE *fp;
	BITFILE *bf;

	if( 4>argc){
		fprintf( stdout, "usage: \n%s <o> <ifile> <ofile>\n", argv[0]);
		fprintf( stdout, "\t<o>: E or D reffers encode or decode\n");
		fprintf( stdout, "\t<ifile>: input file name\n");
		fprintf( stdout, "\t<ofile>: output file name\n");
		return -1;
	}
	if( 'E' == argv[1][0]){ // do encoding
		fp = fopen( argv[2], "rb");
		bf = OpenBitFileOutput( argv[3]);
		if( NULL!=fp && NULL!=bf){
			LZWEncode( fp, bf);
			fclose( fp);
			CloseBitFileOutput( bf);
			fprintf( stdout, "encoding done\n");
		}
	}else if( 'D' == argv[1][0]){	// do decoding
		bf = OpenBitFileInput( argv[2]);
		fp = fopen( argv[3], "wb");
		if( NULL!=fp && NULL!=bf){
			LZWDecode( bf, fp);
			fclose( fp);
			CloseBitFileInput( bf);
			fprintf( stdout, "decoding done\n");
		}
	}else{	// otherwise
		fprintf( stderr, "not supported operation\n");
	}
	return 0;
}

LZW编码算法实现与分析

TXT文件编码:

源文件:
LZW编码算法实现与分析
(191字节)

压缩:LZW编码算法实现与分析(290字节)因为字母重复很少,基数不够大

解压:LZW编码算法实现与分析

PNG格式编码:

原图:LZW编码算法实现与分析
(165KB)

压缩后:217KB

解码后图片:LZW编码算法实现与分析

WORDdoxc格式:

原文:LZW编码算法实现与分析
11.9KB

编码后:17.6KB

解码后:LZW编码算法实现与分析