【问题标题】:reading and writing bit to a file C++读取和写入位到文件 C++
【发布时间】: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


【解决方案1】:
/* Write the least significant bit of the argument */
void writeBit(){
  int i; // <-- HERE
  //Flush the buffer
  if(nbits == 8){
   out.put(buf);
   out.flush();
   bufi = 0;
   buf = 0;
  }
 buf = buf | (i<<(7-nbits)); //Did it write the right bit to ostream ?
 nbits++;
}

您永远不会为 i 分配任何合理的值。所以当你转移它时,你就是在转移垃圾。

你可能想要:

/* Write the least significant bit of the argument */
void writeBit(int i){
  //Flush the buffer
  if(nbits == 8){
   out.put(buf);
   out.flush();
   bufi = 0;
   buf = 0;
  }
 buf = buf | (i<<(7-nbits)); //Did it write the right bit to ostream ?
 nbits++;
}

另外,向我们展示 BitOutput 的析构函数。那里也很有可能存在错误。

【讨论】:

  • 其实我没有写析构函数,因为我在栈中声明了它
  • @JoeCool 你需要写一个析构函数。否则,你不会总是写最后几位。
  • 我添加了析构函数
  • @JoeCool 您的析构函数不会写入最后几个字节。更糟糕的是,deletes 不是指针。
【解决方案2】:

您的代码:

    //Flush the buffer

    if(nbits == 8){
        out.put(buf);
        out.flush();
        bufi = 0;
        buf = 0;
    }

不将 nbits 重置为 0。

【讨论】:

    猜你喜欢
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 2020-04-16
    • 2020-05-23
    相关资源
    最近更新 更多