我试图编码和解码C++中的Huffman编码。我不确定我的问题在哪里,我可以读写,但是当我解压缩文件时,它会乱码,所以我要么不能正确编码或解码。 我认为它是在我写作和阅读出现问题的文件时。所以这就是我必须编写的编码文件。首先,我都从我叫UMAP无序地图bitcodes存储到一个字符串:在C++中对Huffman编码进行一点一点的读写
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();
这是使用调试器一个典型的例子。笔和纸也可能有帮助。这对于简单的代码审查看起来太复杂了。 – 2014-10-18 16:57:20