rle.c

来自「压缩算法的C语言源程序」· C语言 代码 · 共 93 行

C
93
字号
/*
   rle.c
   Run length encoding/decoding for gsLib
*/
#include <compress.h>

static STREAM *in, *out;
static dword bytesread, byteswritten, readlimit, writelimit;

// defines a few helper macros for file io transfer
inline static int getByte()
{
   if(bytesread < readlimit) {
      bytesread++;
      return stream_getc(in);
   }
   return -1;
}

inline static void putByte(int ch)
{
   if(byteswritten < writelimit) {
      byteswritten++;
      stream_putc(ch,out);
   }
}

/*
   dword rle_encode(STREAM *dest,STREAM *src,dword length):
   Encodes the stream `dest' to `src' using the RLE algorithm
   Returns the number of bytes written
*/
dword rle_encode(STREAM *dest,STREAM *src,dword length)
{
   int current, runcount, code = 0;

   in = src;
   out = dest;
   bytesread = byteswritten = 0;
   readlimit = length;
   writelimit = 0xFFFFFFFF;

   current = getByte(); // grab first byte
   while(bytesread <= length) {
      runcount = 0;
      while(runcount < 0x3F && bytesread <= length) {
         runcount++;
         code = getByte();
         if(code != current && code != EOF) break;
      }

      if(runcount > 1) {
         putByte(0xc0 + runcount);
         putByte(current);
      } else {
         if(current >= 0xc0) putByte(0xc1);
         putByte(current);
      }
      current = code;
   }

   return byteswritten;
}

/*
   dword rle_decode(STREAM *in,STREAM *out,dword length):
   Decodes the stream `dest' to `src' using the RLE algorithm
   Returns the number of bytes written
*/
dword rle_decode(STREAM *dest,STREAM *src,dword length)
{
   int i, code, runcount;

   in = src;
   out = dest;
   bytesread = byteswritten = 0;
   readlimit = length;
   writelimit = 0xFFFFFFFF;

   while(byteswritten < length) {
      runcount = 1;
      code = getByte();
      if(code == EOF) break;
      if((code & 0xc0) == 0xc0) {
         runcount = code & 0x3f;
         code = getByte();
      }
      for(i = 0; i < runcount; i++) putByte(code);
   }

   return byteswritten;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?