我正在进行哈夫曼编码的工作,已经构建出字符频率表。
std::map<char,int> frequencyTable;
然后我建立了Huffman树,之后按照以下方式建立了编码表:
std::map<char,std::vector<bool> > codes;
现在我要逐个字符读取输入文件,并通过编码表对它们进行编码,但我不知道如何将位写入二进制输出文件。有什么建议吗?
更新: 现在我正在尝试使用以下函数:
void Encoder::makeFile()
{
char c,ch;
unsigned char ch2;
while(inFile.get(c))
{
ch=c;
//send the Huffman string to output file bit by bit
for(unsigned int i=0;i < codes[ch].size();++i)
{
if(codes[ch].at(i)==false){
ch2=0;
}else{
ch2=1;
}
encode(ch2, outFile);
}
}
ch2=2; // send EOF
encode(ch2, outFile);
inFile.close();
outFile.close();
}
还有这个:
void Encoder::encode(unsigned char i, std::ofstream & outFile)
{
int bit_pos=0; //0 to 7 (left to right) on the byte block
unsigned char c; //byte block to write
if(i<2) //if not EOF
{
if(i==1)
c |= (i<<(7-bit_pos)); //add a 1 to the byte
else //i==0
c=c & static_cast<unsigned char>(255-(1<<(7-bit_pos))); //add a 0
++bit_pos;
bit_pos%=8;
if(bit_pos==0)
{
outFile.put(c);
c='\0';
}
}
else
{
outFile.put(c);
}
}
但是,我不知道为什么,它不起作用,循环从未执行过,编码函数也从未被使用,为什么呢?