0
点赞
收藏
分享

微信扫一扫

数据压缩|LZW编解码算法

罗蓁蓁 2022-04-17 阅读 55
c++

一、 实验目的:掌握词典编码的基本原理,编程实现LZW解码器并分析编解码算法。

二、 实验原理:

1.LZW编码原理:LZW编码的核心思想就是不断地从字符流中提取字符串,之后用码字来表示,这样,对字符流的编码就变成了用码字去替换字符流,生成码字流,从而达到数据压缩的目的。

LZW编码算法的基本步骤如下:

步骤1:词典初始化,该词典包含所有的单字符,当前前缀P初始化为空。

步骤2:当前字符C=字符流的下一个字符

步骤3:判断P+C是否在词典中:

如果在词典中,则P=P+C,返回步骤2;

如果不在词典中,输出与当前前缀相对应的码字;将P+C添加到词典中;P=C,返回步骤2

2.LZW解码原理:LZW解码算法,解码词典和编码词典相同,包含所有可能的单字符,即前缀根。

具体步骤如下:

步骤1:词典初始化

步骤2:CW:=码流中第一个码字

步骤3:输出当前缀字符串(即CW对应的码字)到码字流

步骤4:先前码字:PW=当前码字CW

步骤5:当前码字CW=码字流中下一个码字

步骤6:判断当前缀字符串(CW)是否在词典中

如果在,将(CW对应的码字)输出到码字流中,将P+C添加到词典

如果不在,将P+C输出到字符流,并且把它添加到词典中

步骤7:判断是否还有码字要译

如果是,返回4;否则结束。

三、主要代码实现(重要语句注释已经在代码中给出)

bitio.h

/*
* 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>
BITFILE *OpenBitFileInput( char *filename){
BITFILE *bf;
bf = (BITFILE *)malloc( sizeof(BITFILE));
if( NULL == bf) return NULL;
if( NULL == filename) bf->fp = stdin;
else fopen_s(&(bf->fp), 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 fopen_s(&(bf->fp),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->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

LZW.cpp

/*
* 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对应的后缀输出到字符流中
code = dictionary[code].parent;/code对应于字典中code的母节点
count++;更新
}
return count;
}
void InitDictionary( void){///初始化
int i;

for( i=0; i<256; i++){
dictionary[i].suffix = i;///设置后缀
dictionary[i].parent = -1;///设置母节点为-1,即母节点不存在
dictionary[i].firstchild = -1;设置孩子节点为-1,即孩子节点不存在
dictionary[i].nextsibling = i+1;设置下一个兄弟节点为i+1
}
dictionary[255].nextsibling = -1;规定dictionary[255]下一个兄弟节点为-1,即不存在下一个兄弟节点
next_code = 256;//设置下一个编号为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;如果编号小于0,则character为单个字符,直接输出即可
sibling = dictionary[string_code].firstchild;//否则,设置dictionary[string_code]的第一个孩子节点
while( -1<sibling){//
if( character == dictionary[sibling].suffix) return sibling;如果character等于编号为sibling的字符串的话,返回编号即可
sibling = dictionary[sibling].nextsibling;///否则,将sibling一直推进即可,直到找到
}
return -1;
}

void AddToDictionary( int character, int string_code){///添加新词条到词典里
int firstsibling, nextsibling;
if( 0>string_code) return;//如果string_code小于0,则character为单个字符,直接输出即可
dictionary[next_code].suffix = character;/添加character到词典里
dictionary[next_code].parent = string_code;//设置其母节点的编号
dictionary[next_code].nextsibling = -1;/设置下一个兄弟节点为-1,即不存在
dictionary[next_code].firstchild = -1;/设置下一个孩子节点为-1,即不存在
firstsibling = dictionary[string_code].firstchild;//设置string_code的第一个孩子节点
if( -1<firstsibling){ // the parent has child 即string_code 在添加character之前存在孩子节点
nextsibling = firstsibling;
while( -1<dictionary[nextsibling].nextsibling ) /判断是否有下一个兄弟结点
nextsibling = dictionary[nextsibling].nextsibling;
dictionary[nextsibling].nextsibling = next_code;如果没有兄弟节点的话,设置next_code ,本判断旨在说明新添加的词条与之前string_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;///让character作为母节点,继续向下查找
}
}
output( bf, string_code);
}

void LZWDecode( BITFILE *bf, FILE *fp){///解码部分
int character;
int new_code, last_code;/CW,PW
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);/判断更新后的CW是否在词典中
if (new_code >= next_code) {//如果读入的不在字典中
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) {如果字典中还有空间时
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
fopen_s(&fp,argv[2], "rb");//打开文件
bf = OpenBitFileOutput( argv[3]);
if( NULL!=fp &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]);
fopen_s( &fp,argv[3], "wb");
if( NULL!=fp &bf){
LZWDecode( bf, fp);
fclose( fp);
CloseBitFileInput( bf);
fprintf( stdout, "decoding done\n");
}
}else{ // otherwise
fprintf( stderr, "not supported operation\n");
}
return 0;
}

四、实验结果:

1.调试了LZW的编码程序,得到输出的LZW编码文件。

2.解码程序中已在代码部分加上注释。字符不存在于词典中,cW的映射为P+C,cW的第一个字符为pW的第一个字符;将倒序存入的堆栈逆序取出并输出到文件中。

3.

文件类型

编码前文件大小

编码后文件大小

压缩效率

docx

12.3 KB

18.4 KB

-49.6%

pptx

34.0 KB

45.8 KB

-34.7%

jpg

29.4 KB

32.1 KB

-9.1%

gif

3.32 KB

5.84 KB

-75.9%

tif

7.29 KB

13.4 KB

-83.8%

bmp

2.13 MB

6.49 KB

+

png

5.90 KB

6.08 KB

-3.1%

rtf

39.9 KB

18.3 KB

54.1%

tsv

31.2 MB

5.08 MB

83.7%

rgb

192 KB

178 KB

7.3%

pdf

2.67 MB

3.19 MB

-19%

根据实验结果可以看出,文件类型不同经过LZW编码器编码后是否压缩是不同的,例如,docx,pdf等压缩变大,rtf,tsv等压缩变小符合预期。

举报

相关推荐

0 条评论