来自:http://blog.csdn.net/calcular/article/details/46804919
自己用c写了个rle压缩编码算法,代码写得不那么简洁,但是基本功能是实现的,用C写能更好地兼容嵌入式
/*
行程压缩算法V1.0
made by xyt
2015/7/4
*/
#ifndef _RLE_H
#define _RLE_H
#include<stdio.h>
using namespace std;
//判断是否三个相同值
bool IsRepeat3(unsigned char *in,int rest)
{
if(rest<2) return false;
else{
if(*in==*(in+1)&&*in==*(in+2)) return true;
else return false;
}
}
/* 获取非重复个数,个数为包括判决项直到后面
第一次三连重复的(三重复第一点不算)的个数 */
int GetNoRepeat3(unsigned char *in,int rest)
{
if(rest<=2) return rest+1;
else{
int c=0,restc=rest;
unsigned char *g=in;
while(!IsRepeat3(g,restc))
{
g++;restc--;c++;
if(restc==0) return c+1;
}
return c;
}
}
/* 数据压缩,返回压缩后数据大小 */
int Rle_Encode(unsigned char *inbuf,int insize,unsigned char *outbuf1,int outsize)
{
unsigned char *src=inbuf;
unsigned char *outbuf=outbuf1;
int rest=insize-1;
int outrest=outsize;
int count=0;
while(rest>=0)
{
count=0;
if(IsRepeat3(src,rest))
{
while(rest>=0)
{
if(count>=127) break;
if(*src==*(src+1)){src++; rest--; count++;}else{count++; break;}
}
if(outrest<2) return -1;
*outbuf=count|128;
outbuf++;
*outbuf=*src;
outbuf++;
outrest-=2;
src++;rest--;
}
else
{
if(IsRepeat3(src,rest)) continue;
int num=GetNoRepeat3(src,rest);
int i;
if(outrest<(num+1)) return -1;
*outbuf=num;outbuf++;
for(i=0;i<num;i++){
*outbuf=*(src+i);
outbuf++;
}
src+=num;
rest-=num;
outrest-=num+1;
}
}
return outsize-outrest;
}
/* 解压数据,返回解压数据大小 */
int Rle_Decode(unsigned char *inbuf,int insize,unsigned char *outbuf,int outsize)
{
int inrest=insize;
int outrest=outsize;
int i;
unsigned char *in=inbuf;
unsigned char *out=outbuf;
unsigned char ns;
unsigned char tmp;
while(inrest>=0)
{
ns=*in;
if(ns==0) break;
if(ns>128){
if((outrest-ns+128)<0) return -1;
tmp=*(in+1);
for(i=0;i<ns-128;i++){
*out=tmp;
out++;
}
in+=2;inrest-=2;outrest-=ns-128;
}else{
if((outrest-ns)<0) return -1;
in++;
for(i=0;i<ns;i++){
*out=*in;
out++;in++;
}
inrest-=1+ns;outrest-=ns;
}
}
return outsize-outrest;
}
#endif