資源簡介
使用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:?“?<????for?(int?i?=?0;?i?128;?i++)?{
????????if?(freq[i])?{
????????????ch?=?(char)?i;
????????????probability?=?(double)?freq[i]?/?(double)?strlen(str);
????????????cout?<????????????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:?“?<????cout?<“Binary?code:?“;
????dec2bin(encode(str));
????cout< ????cout?<“Compression?rate:?“?<????cout?<????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語言課程設計景區管理系統
評論
共有 條評論