一.实验目的
掌握词典编码的基本原理,用C/C++/Python等语言编程实现LZW解码器并分析编解码算法。
二.实验原理
编码原理
解码原理
代码实现
LZW.C
/*
* Definition for LZW coding
*
* vim: ts=4 sw=4 cindent nowrap
*/
#include <stdlib.h>
#include <stdio.h>
#include "bitio.h"
#define MAX_CODE 65535
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){
//初始化词典,将256以内的ASCII码初始化到表中
int i;
for( i=0; i<256; i++){
dictionary[i].suffix = i;//码字的ASCII码
dictionary[i].parent = -1;//因为是256以内所以没有parent
dictionary[i].firstchild = -1;//因为是256以内所以没有firstchild
dictionary[i].nextsibling = i+1;//nextsibling即是下一个ASCII码
}
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 s