LZW编码

一.实验目的

掌握词典编码的基本原理,用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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值