资源简介
使用c++实现的算术编码,从屏幕读入一个字符串并输出十进制及二进制编码,并计算压缩率,字符概率自动统计生成

代码片段和文件信息
#include “arithmetic.h“
void Arithmetic::getProbabilities(char *str) {
char ch;
double lowLevel = 0.0;
double highLevel = 0.0;
double probability;
int freq[128] = {0};
for (int i = 0; str[i]; i++)
freq[str[i]]++;
cout << “The probability of each char: “ << endl;
for (int i = 0; i < 128; i++) {
if (freq[i]) {
ch = (char) i;
probability = (double) freq[i] / (double) strlen(str);
cout << ch << “: “ << probability << endl;
lowLevel = highLevel;
highLevel = lowLevel + probability;
Range range;
range.setLow(lowLevel);
range.setHigh(highLevel);
range.setDelta(probability);
map.insert(std::pair(ch range));
}
}
}
double Arithmetic::encode(string str) {
double lowRange = 0.0 highRange = 1.0;
for (char &i : str) {
// 使用map来通过字符完成概率的查找
// map[*i]表示的就是对应的字符的出现概率
double delta = highRange - lowRange;
highRange = lowRange + delta * map[i].getHigh();
lowRange = lowRange + delta * map[i].getLow();
++length;
}
return lowRange;
}
void Arithmetic::runArithmetic() {
long beginT = clock();
cout << “Please enter a string:“;
char str[1024];
cin>>str;
getProbabilities(str);
long endT = clock();
long costT = endT - beginT;
cout << “Resulting code: “ << encode(str) << endl;
cout << “Binary code: “;
dec2bin(encode(str));
cout< cout << “Compression rate: “ << double(binLength) / double(strlen(str) * 8) << endl;
cout << endl << “Time costs: “ << costT << “ ms“ << endl;
cin.clear();
cin.sync();
}
void Arithmetic::dec2bin(double n) {
stack s;
int m = (int) n;
double t = n - m;//0.4
binLength = 0;
while (m) // 处理整数
{
s.push(m % 2);
m /= 2;
}
while (!s.empty()) {
printf(“%d“ s.top());
s.pop();
}
printf(“0.“);
while (t - int(t) != 0) //处理小数点后的位数,乘2取整法 ,当乘2变为整数后结束
{
int temp = int(t * 2);
printf(“%d“ temp);
binLength++;
t = 2 * t - int(2 * t);
}
}
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 2433 2018-12-22 00:16 arithmetic.cpp
文件 1216 2018-12-21 23:29 arithmetic.h
- 上一篇:自适应哈夫曼编码C++
- 下一篇:C语言课程设计景区管理系统
相关资源
- 国际象棋的qt源代码
- C++中头文件与源文件的作用详解
- C++多线程网络编程Socket
- VC++ 多线程文件读写操作
- 利用C++哈希表的方法实现电话号码查
- 移木块游戏,可以自编自玩,vc6.0编写
- C++纯文字DOS超小RPG游戏
- VC++MFC小游戏实例教程(实例)+MFC类库
- 连铸温度场计算程序(C++)
- 6自由度机器人运动学正反解C++程序
- Em算法(使用C++编写)
- libstdc++-4.4.7-4.el6.i686.rpm
- VC++实现CMD命令执行与获得返回信息
- 白话C++(全)
- C++标准库第1、2
- 大数类c++大数类
- C++语言编写串口调试助手
- c++素数筛选法
- C++ mqtt 用法
- 商品库存管理系统 C++ MFC
- c++ 多功能计算器
- C++17 In Detail
- 嵌入式QtC++编程课件
- 颜色识别形状识别STM103嵌入式代码
- c++ 邮件多附件群发
- c++ 透明代理(hookproxy)
- mfc 调用redis
- FTP客户端源码(c++)
- c++ 画图(14Qt-XPS)
- c++多边形交并差运算
评论
共有 条评论