#include "stdio.h"
#include "assert.h"
#include "math.h"
#include "shannan.h"
#ifndef NULL
#define NULL 0
#endif
CShannan::CShannan(int n)
{
assert(n>0);
m_n=n;
m_p=new float[n];
m_sp=new float[n];
m_i=new float[n];
m_length=new int[n];
m_code =new U32[n];
assert(m_p!=NULL);
assert(m_sp!=NULL);
assert(m_i!=NULL);
assert(m_length!=NULL);
assert(m_code!=NULL);
}
CShannan::~CShannan()
{
if(m_p)
delete[]m_p;
if(m_sp)
delete[]m_sp;
if(m_i)
delete[]m_i;
if(m_length)
delete[]m_length;
if(m_code)
delete[]m_code;
}
int CShannan::cpux86()
{
union
{
char a[2];
short int b;
}test;
test.b=1;
if(test.a[0]==1)
return 1;//低位在前
return 0;//高位在前
//test needed
}
void CShannan::InputPro()
{
float last=1.0f;
int i;
for(i=0;i<m_n-1;++i)
{
while(1)
{
printf("输入第%d个消息概率:",i+1);
scanf("%f",m_p+i);
if(m_p[i]<last)
{
last-=m_p[i];
break;
}
else
{
printf("错误,输入概率值必须小于%.4f\n",last);
}
}
}
m_p[m_n-1]=last;
printf("第 %3d 个消息概率值为 %.4f\n开始香农编码...\n",m_n,last);
//Shannan Code
//Sort
for(i=0;i<m_n;++i)
{
for(int j=i+1;j<m_n;++j)
{
if(m_p[j]>m_p[i])
{
float tmp=m_p[i];
m_p[i]=m_p[j];
m_p[j]=tmp;
}
}
}
float a=(float)(-1.0/log(2.0));
for(i=0;i<m_n;++i)
{
m_sp[i]=i>0?m_sp[i-1]+m_p[i-1]:0.0f;
float inf=(float)(a*log(m_p[i]));
m_i[i]=inf;
m_length[i]=(int)inf;
if((float)m_length[i]<inf)
++m_length[i];
}
//由IEEE-754浮点数存储格式标准,直接由累加概率值中取出CODE
for(i=0;i<m_n;++i)
{
U32 *d=(U32*)(m_sp+i);
S8 move=(S8)(((((*d) >> 23) & 0xFF) + 0x1) ^ 0x80);//得到移阶码对应的补码,单精度型的偏移量是0x7F
m_code[i]=(((*d) & 0x7FFFFF) | 0x800000) >> (-move-1);//补上隐含位并对阶后的尾数
}
//End Code
printf("编码完毕!\n");
}
void CShannan::OutputCode()
{
printf("-=-=-=-=-=-=-\n香农编码结果:\n-=-=-=-=-=-=-\n");
printf("消息序号si 消息概率p(si) 累加概率Pi -log p(si) 代码组长度li 二进制代码组\n");
for(int i=0;i<m_n;++i)
{
printf(" s%-5d %-10.4f %-8.4f %-8.4f %-7d ",i+1,m_p[i],m_sp[i],m_i[i],m_length[i]);
for(int j=0;j<m_length[i];++j)
{
if((m_code[i] >> (23-j)) & 0x1)
printf("1");
else
printf("0");
}
printf("\n");
}
}
#include "shannan.h"
#include <stdio.h>
int main()
{
int n;
printf("输入消息符号个数N:");
scanf("%d",&n);
CShannan scode(n);
scode.InputPro();
scode.OutputCode();
return 0;
}
香农编码-C++
5星 · 超过95%的资源 需积分: 9 84 浏览量
2008-06-24
16:56:22
上传
评论 1
收藏 214KB RAR 举报
bingzi584520
- 粉丝: 0
- 资源: 5
最新资源
- 基于Matlab人脸肤色定理的教师人数统计+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于Matlab霍夫曼变换的表盘读数识别+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于Matlab火灾烟雾检测源码带GUI界面+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于Matlab的恶劣天气交通标志识别系统+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于MATLAB的霍夫曼变换的表盘示数识别+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于Matlab的车道线识别系统 +源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于MATLAB的教室人数统计系统带Gui界面+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于MATLAB的教室人数统计系统带Gui界面+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于MATLAB 的霍夫曼变换答题卡识别源码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
- 基于Matlab+bp神经网络的神经网络汉字识别系统+源代码+全部数据+文档说明+详细注释+使用说明+截图(高分课程设计)
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈