?? arithmetic-coding.c
字號:
#include <stdio.h>
#include <string.h>
#define max 20
void main()
{
char a[max];
float sl[max],sh[max],L[max],H[max],p[max],ch[max];
int i,j,m,tag,k;
float temp;
u: printf("輸入待編碼字符串:");
gets(a);
m=strlen(a);
//概率及區間劃分
for(i=0;i<m;i++)p[i]=0;
for(i=0;i<m;i++){
for(j=0;j<m;j++)
{if(a[j]==a[i]) p[i]++;}
ch[i]=(float)p[i]/m;}
sh[0]=ch[0];sl[0]=(float)0;
temp=sh[0];
printf("\n字符概率及區間劃分:\n");
printf("字符%c 概率:%f 區間:sl=%f sh=%f\n",a[0],(p[0]/m),sl[0],sh[0]);
for(i=1;i<m;i++)
{ tag=1;
for(j=0;j<i;j++)
{
if (a[j]==a[i]) {sl[i]=sl[j];sh[i]=sh[j];tag=0;}
}
if(tag==1) {sl[i]=temp;sh[i]=temp+ch[i];temp=sh[i];
printf("字符%c 概率:%f 區間:sl=%f sh=%f\n",a[i],(p[i]/m),sl[i],sh[i]);}
}
//算術編碼
L[0]=sl[0];H[0]=sh[0];temp=H[0]-L[0];
for(i=1;i<m;i++)
{
L[i]=L[i-1]+temp*sl[i];
H[i]=L[i-1]+temp*sh[i];
temp=H[i]-L[i];
}
printf("\n算術編碼結果:\n");
for(i=0;i<m;i++)
{printf("a%d-L=%f ",i,L[i]);printf("a%d-H=%f \n",i,H[i]);}
//算術解碼
float b,UL,UH;
char s[max];
k=0;
UL=0;
UH=(float)1;
b=H[m-1];
temp=(float)1;
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
if(((b-UL)/temp>=sl[j])&&((b-UL)/temp<=sh[j]))
{s[k++]=a[j];
UH=UL+temp*sh[j];UL=UL+temp*sl[j];temp=UH-UL;
}
}
printf("\n算術解碼結果:");
for(i=0;i<m;i++)printf("%c",s[i]);
printf("\n\n\n");
goto u;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -