萌新自己写的一些关于哈夫曼树的压缩以及解压缩,欢迎大佬指导
void HuffmanTree::getiosnum(unsigned char c, unsigned char iosarray[8])//获取字符c的二进制编码,用长度为8的数组存储返回,在译码时用到
{
int x = (int)c;
int p = 1, y = 0, yushu, i = 7;
while (1)
{
yushu = x % 2;
x /= 2;
iosarray[i] = yushu + 48;//
–i;//
if (x < 2){ iosarray[i] = x + 48; break;}//if
}//while
}
void HuffmanTree::Encoding()//编码
{
string s, cod, codios;
unsigned char c;
fstream file(“CodeFile.txt”, ios::out|ios::binary);//打开存储压缩了编码的文件
fstream outfile(“CodePrin.txt”, ios::out);//用来存储字符型式‘0’‘1’的文件
Getnumber(root, s);//获取哈夫曼树的字符对应的01编码
fstream fp;
int num = 0;
//fp.open(“ToBeTran.txt”, ios::in);
fp.open(“book.txt”, ios::in);//打开待压缩的未编码文件
//cout << “原文件ToBeTran的数据。” << endl;//测试文件
while (fp.read((char*)&c, sizeof©)) {
cout << c;
for (int n = 0; n < i; n++) {
if (c == Codesave[n].data) cod += Codesave[n].code;
}//与之前编码的个字符匹配编码,编码成字符型0.1,加入string cod中
}
outfile << cod;
outfile.close();
//压缩编码系统
num = 0;
int number=0;
for (int n = 0; n < cod.length(); n++) {
number += ((int)cod[n]-48)pow(2, 7 - num);
num++;
if (num % 8 == 0 ) {//将字符型的0,1转化成十进制,满八位转换成unsigned char字符输出到文件
c = number;
file << c;
number = num = 0;
}
}
///还没写好的,编码文件的最后如果不满八位的情况
if (num % 8 != 0) {
c = number;
unsigned char arr[8];
getiosnum(c, arr);
for (int i = 0; i < 8; i++) {
if (num > 0) { arr[i] = arr[8 - num]; num–; }
else arr[i] = ‘0’;
}
number = 0;
for (int i = 0; i < 8; i++) {
number += ((int)arr[i] - 48)pow(2, 7 - i);
}
cout << number << endl;
c = number;
file << c;
}/
//file << codios;
//file << cod;
file.close();
fp.close();
}
void HuffmanTree::Decoding() {//译码
unsigned char c;
HuffmanNode p = root;
fstream file(“CodeFile.txt”, ios::in|ios::binary);
fstream fp(“TextFile.txt”, ios::out);
cout << “将已编码文件CodeFile转变成原有的字符为:” << endl;
while (file.read((char)&c, sizeof©)) {
unsigned char arr[8];
for (int i = 0; i < 8; i++) arr[i] = ‘0’;//初始化数组
getiosnum(c,arr);//获取字符c对应的二进制编码
for (int i = 0; i < 8; i++) {//哈夫曼树译码
if (arr[i] == ‘0’) { p = p->leftchild; }
else if (arr[i] == ‘1’) { p = p->rightchild; }
if (p->leftchild == 0 && p->rightchild == 0)
{
cout << p->data; fp << p->data; p = root;
}
}
}
cout << endl;
}
自写哈夫曼树的文件压缩和解压
最新推荐文章于 2021-09-23 08:36:38 发布