Visitors hit counter dreamweaver

多媒体技术 有损压缩算法之算术编码

      算术编码是一种更现代的编码,在实际中比Huffman编码更有效。算术编码把整个消息看做一个单元。具体的实现也很方便。根据书上的伪代码,很快就能把程序写出来。下面是我写的程序。

#include <iostream>
#include <fstream>
#include <string>
#include <queue>
#include <math.h>


using namespace std;

typedef struct{
     char symbol;
     float range,low,high;
}Team; 
Team in[100];

float Expo(int k)
{
    int i;
    float sum=1.0;
    for(i=0; i<k; i++)
    {
         sum=sum*2e-1;
    }
    return sum;
}

int main()
{
      int i=0,j=0,k=1;
      float low=0.0,high=1.0,range=1.0,code=0.0;
      string str;  //存储小数点后面的数字  即总共需要的位数
      freopen("in.txt","r",stdin);
      while( (scanf("%c%f",&in[i].symbol,&in[i].range))!=EOF )
      {
            in[i].low=low; in[i].high=low+in[i].range;
            low=in[i].high;
            i++;
        getchar();
      }

      freopen("in2.txt","r",stdin);
      char c;
      queue<char> q;
      while( scanf("%c",&c)!=EOF)
      {
         q.push(c);
      }
      low=0.0;
      //编码
      while(!q.empty())
      {
          c=q.front();
          q.pop();
          for(j=0; j<i; j++)
          {
              if(in[j].symbol==c)
                  break;
          }
          high=low+range*in[j].high;
          low=low+range*in[j].low;
          range=high-low;
          j++;
      }

      //产生码字
      float e;
      while(code<low)
      {
          e=pow(2,-k);
          code+=e;
          if(code<=high)
              str.append("1");
          else
          {
              code-=e;
              str.append("0");
          }
          k++;
      }
      cout<<str<<endl;
    return 0;
}

 

posted @ 2012-04-09 23:45  Jason Damon  阅读(1124)  评论(0编辑  收藏  举报