读入二进制文本文件,统计并做一些计算
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
int cbtoi(char* ch) //哈希函数,将输入的8位二进制数的char[]转换成十进制数
{
int v=0;
for(int i=0;i<8;i++)
if(ch[i]=='1')
v+=(1<<(7-i));
return v;
}
int main()
{
ifstream inf("D:/in.txt");
int count[256]={0};
int count_p[70000]={0};
int c_total=1;
char c;
char chf[9]="EEEEEEEE";
inf.get(chf,9);//第一个元素,特殊处理。。
while(chf[7]=='E' || chf[7]=='/n')
{
inf.get();
inf.get(chf,9);
}
count[cbtoi(chf)]++;//cbtoi(chf)为第一个元素的十进制值
int pre_elem=cbtoi(chf);
while((c = inf.get())!= EOF)
{
if(c=='/n') //到达换行符,吃掉
continue;
char ch[9]="EEEEEEEE"; //初始化为"EEEEEEEE",作剔除检验
inf.putback(c);
inf.get(ch,9);
if(ch[7]=='E' || ch[7]=='/n') //尾数不足8位,剔除
continue;
count[cbtoi(ch)]++;//读入哈希表
count_p[(pre_elem<<8)+cbtoi(ch)]++;//读入对的哈希表,pre_elem<<8+cbtoi(ch) 是另外一个哈希表的哈希函数
c_total++;
pre_elem=cbtoi(ch);
}
if(count[cbtoi(chf)]==1)//判断第一个是不是si,如果只出现一次的话就不是,剔除
count[cbtoi(chf)]=0;
double p_si;
double p_sji;
double H0=0;
double H1=0;
for(int i=0;i<256;i++)
if(count[i])
{
cout<<hex<<i<<dec<<'/t'<<"H="<<log(count[i])/log(2)<<"/t";//输出H
p_si=double(count[i])/double(c_total);
// cout<<"p(si)="<<p_si; //输出p(si)
cout<<endl;
H0+=(p_si*(log(p_si)/log(2)));
double temp=0; //保存E[P(Sj|Si)*log(P(Sj|Si))]
for(int k=0;k<=256;k++)
{
int j=(k<<8)+i;
if(count_p[j])
{
p_sji=double(count_p[j])/double(c_total-1);
temp+=(p_sji*(log(p_sji)/log(2)));
}
}
H1+=(p_si*temp);
}
cout<<endl<<"H0="<<-H0<<endl;
cout<<"H1="<<-H1<<endl;
/*for(int j=0;j<70000;j++)
if(count_p[j])
{
cout<<hex<<j<<dec<<'/t'<<count_p[j]<<'/t';
p_sji=double(count_p[j])/double(c_total-1);
cout<<p_sji<<endl;//输出p(sj|si)
}
cout<<c_total<<endl;*/
return 0;
}