LZW解码原理和实现算法及效率评估

本文介绍了LZW解码的基本原理和详细步骤,包括解码算法的流程,以及如何实现这一算法。通过解码过程,将码字流转换为字符流,并不断更新词典。同时,文中提到使用LZW算法对docx、txt等十种不同格式的文件进行编码和解码,得出各格式的内存压缩比例。
摘要由CSDN通过智能技术生成

在这里插入图片描述

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)如果”否”,结束。
LZW解码算法可用下述函数实现。首先初始化词典,然后顺序从压缩文件中读入码字并按照上述算法执行解码。最后将解得的字符串输出至文件中。

代码头文件

#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	

代码主函数

//lab6tyx
#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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值