LZW 编解码算法实现与分析

本文介绍LZW压缩算法原理及其实现过程,包括编码与解码的步骤,并提供C语言编写的完整源代码示例。通过对多种文件类型的压缩实验,探讨了LZW算法的实际效果。

实验目的

掌握词典编码的基本原理,用C/C++/Python等语言编程实现LZW解码器并分析编解码算
法。

方法解释

算法说明

所用功能代码

词典树数组结构体

struct {
	int suffix;//后缀
	int parent;//母节点 
	int firstchild;//第一子节点
	int nextsibling;//下一个相邻同级节点
} dictionary[MAX_CODE + 1];

词典初始化

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;
}

词典添加字符

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++;
}

LZW编码原理和实现算法

原理

        LZW的编码思想是不断地从字符流中提取新的字符串,通俗地理解为新“词条”,然后用“代号”也就是码字表示这个“词条”。这样一来,对字符流的编码就变成了用码字去替换字符流,生成码字流,从而达到压缩数据的目的。LZW编码是围绕称为词典的转换表来完成的。LZW编码器通过管理这个词典完成输入与输出之间的转换。LZW编码器的输入是字符流,字符流可以是用8位ASCII字符组成的字符串,而输出是用n位(例如12位)表示的码字流。LZW编码算法的步骤如下:
        步骤1:将词典初始化为包含所有可能的单字符,当前前缀P初始化为空。

        步骤2:当前字符C=字符流中的下一个字符。
        步骤3:判断P+C是否在词典中
         (1)如果“是”,则用C扩展P,即让P=P+C,返回到步骤2。
         (2)如果“否”,则
                输出与当前前缀P相对应的码字W;
                将P+C添加到词典中;
                令P=C,并返回到步骤2

代码实现

LZW编码

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);
}

LZW解码原理和实现算法

原理

        LZW解码算法开始时,译码词典和编码词典相同,包含所有可能的前缀根。具体解码算法如下:
        步骤1:在开始译码时词典包含所有可能的前缀根。
        步骤2:令CW:=码字流中的第一个码字。
        步骤3:输出当前缀-符串string.CW到码字流。
        步骤4:先前码字PW:=当前码字CW。
        步骤5:当前码字CW:=码字流的下一个码字。
        步骤6:判断当前缀-符串string.CW 是否在词典中。
        (1)如果”是”,则
                把当前缀-符串string.CW输出到字符流。
                当前前缀P:=先前缀-符串string.PW。
                当前字符C:=当前前缀-符串string.CW的第一个字符。
                把缀-符串P+C添加到词典。
        (2)如果”否”,则
                当前前缀P:=先前缀-符串string.PW。
                当前字符C:=当前缀-符串string.CW的第一个字符。
                输出缀-符串P+C到字符流,然后把它添加到词典中。
        步骤7:判断码字流中是否还有码字要译。
        (1)如果”是”,就返回步骤4。
        (2)如果”否”,结束。

重要问题

对原理步骤6:(2)的解释
        解码时,出现词典中无法查询到该字符,是由于在编码时,新的“P+C”刚被创建,下一个“P”就需要使用它造成的,新创建的“P+C”的尾缀是新创建的“P+C”的首字符“

代码实现
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);//返还1

		}
		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;
	}

}

实验结果

调试LZW编解码程序

在这里插入图片描述
设置项目参数 进行编码
在这里插入图片描述
编码生成文件
在这里插入图片描述
设置项目参数 解码
在这里插入图片描述
解码生成文件,与原文件一致
在这里插入图片描述
在这里插入图片描述

选择至少十种不同格式类型的文件,使用LZW编码器进行压缩

在这里插入图片描述

文件类型原始文件大小LZW编码压缩后大小压缩比
docx620,942771,188124.2%
bmp3,03098032.3%
rgb196,608183,27293.2%
yuv98,30469,63470.8%
pdf211,722271,978128.4%
jpg170,416197,340115.8%
txt3,9462,14454.3%
png55,23882,704149.7%
eddx33,47754,948164.1%
zip505,449640,588126.7%

由表格可知,LZW压缩频繁出现压缩或文件变得更大的情况,猜测是该代码程序的局限性所致。所以个人认为,这些压缩比并不准确。

完整代码

bitio.h头文件

bitio.c定义码流输入输出函数

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

#include <stdlib.h>
#include <stdio.h>
#include "bitio.h"
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;
	}
}

lzw_E.c 定义编解码函数、main函数所在

/*
 * 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) {
	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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值