【发布时间】:2014-12-29 20:26:05
【问题描述】:
我正在编写一个使用 Huffman 算法压缩文本文件的程序。我已经通过将打印的 ASCII 字符打印到文件来测试我的程序,它工作正常。但是,现在我必须使用位来实现,我的程序不起作用。好像我没有读或写正确的位。
这是我的测试结果:
在输入文件中,我将abc 输入文件进行压缩。然后我解压出来是aaa。
下面是我如何读写位的sn-p
class BitInput {
istream& in; // the istream to delegate to
char buf; // the buffer of bits
int nbits; // the bit buffer index
public:
BitInputStream(istream& s) : in(s), buf(0), bufi(8) { }
~BitInputStream //destructor
{
delete in;
};
/** Read the next bit from the bit buffer.
* Return the bit read as the least significant bit of an int.
*/
int readBit(){
int i;
if(nbits == 8){
buf = in.get();
nbits = 0;
}
i = (1 & buf>>(7-nbits)); //This could be the problem, I'm not getting the writing bit
nbits++;
return i;
}
/** Read a char from the ostream (which is a byte)*/
int readChar(){
int sum = 0;
for(int i = 7; i>=0; i--)
sum = (sum*2) + readBit();
return sum;
}
class BitOutput {
ostream& out; // the istream to delegate to
char buf; // the buffer of bits
int nbits; // the bit buffer index
public:
BitOutput(istream& s) : in(s), buf(0), bufi(8) { }
/* Write the least significant bit of the argument */
void writeBit(int i){
//Flush the buffer
if(nbits == 8){
out.put(buf);
out.flush();
nbits = 0;
buf = 0;
}
buf = buf | (i<<(7-nbits)); //Did it write the right bit to ostream ?
nbits++;
}
/** Write a char to the ostream (a byte) */
void writeChar(int ch){
for(int i = 7; i >= 0; i--)
writeBit((ch >> i) & 1);
}
【问题讨论】:
-
我们需要看看BitOutput的析构函数。那里很可能存在错误。
-
哎呀我忘了把 i 放在参数中。我编辑了我的代码
-
标签: c++ bit bitwise-operators huffman-code