【发布时间】:2014-10-18 16:37:46
【问题描述】:
我正在尝试对 C++ 中的霍夫曼编码进行编码和解码。我不确定我的问题出在哪里,我可以读写,但是当我解压缩文件时,它被打乱了,所以我要么编码不正确,要么解码不正确。 我认为当我在编写和读取文件时出现问题。所以这就是我必须编写的编码文件。首先,我将名为 uMap 的无序地图中的所有位码存储到一个字符串中:
int i = 0, j = 0;
string fullStr = "";
for (i = 0; i < buffsize; i++) //put all codes in one string of 1's and 0's
fullStr += uMap[buffer[i]];
unsigned char byte = 0;
i = 0;
for (j = 0; j < fullStr.length(); j++)
{
if (i != 8)
{
byte |= (fullStr[j] == '1') << i; // make up one byte
i++;
}
else
{
outf.put(byte); // write one byte at a time
byte = 0;
i = 0;
}
}
if (i != 0 && i < 8)
{
while (i<8)
{
byte |= 0 << i; // finish up last byte if not finished
i++;
}
outf.put(byte);
}
然后在解压端:
int i = 0;
unsigned char byte = 0;
bitset<8> setByte;
ofstream outf(filename, ofstream::binary);
string concat = "";
string bitStr = "";
for (i = 0; i < buffLength; i++)
{
setByte = buffer[i];
bitStr = setByte.to_string();
for (int j = 0; j < 8; j++)
{
concat += bitStr[j];
if (uMap[concat])
{
//cout << "found code " << concat << " " << uMap[concat] << endl;
outf.put(uMap[concat]);
concat = "";
}
}
}
outf.close();
【问题讨论】:
-
这是使用调试器的主要示例。笔和纸也可能有帮助。对于简单的代码审查来说,这看起来太复杂了。
标签: c++ encoding binary huffman-code