如何保存(和检索)文件的位序列

How to save (and retrieve) to file a sequence of bits

本文关键字:文件 何保存 保存 检索      更新时间:2023-10-16

我想在一个文件中存储一个比特序列。

我尽量只描述最重要的:

  • 我有一个矢量(我知道,不是一个好主意,但我只是简单地使用它)
  • 我想把它存储在一个文件(我使用Linux)
  • 我想从上述文件中检索它并重新创建矢量

由于c++不允许存储单个位,我不得不将所有位分组为char并将char保存为"text"。为此,我使用了http://www.avrfreaks.net/forum/tut-c-bit-manipulation-aka-programming-101

如果位数是8的倍数,则一切正常。如果不是这样,我不知道该如何处理这个问题。

我会解释得更好。我:

010011000110111101110010011001010110110101

我将字符保存为:

01001100 -> L
01101111 -> o
01110010 -> r
01100101 -> e
01101101 -> m
01

最后一个"01"…我不知道怎么储存。当然,我可以创建一个带有1和一些0填充的字节…但当我检索它们时,我不知道"额外比特"的数量!什么是填充,什么是信息?

我不知道该怎么做…任何想法?

文件写入器的一些代码(不是我的实际代码…太长了……我只写了重要的部分…):

void Compressor::compress(std::istream &is, std::ostream &os) {
  queue<bool> bit_buffer;
  char c;
  while (is.get(c)) {
      new_letter = c;
      const std::vector<bool> bit_c = char2bits(new_letter);
      for(bool bit : bit_c) 
        bit_buffer.push(bit);
  }
  //Here my code adds a certain number of bits, I simulate this with:
  bit_buffer.push(false);
  bit_buffer.push(true);
  // Write the bit buffer into a file
  while (bit_buffer.size() >= 8) {
    // Group vector<bool> in char
    char output = 0;
    for (int i=0; i<8; i++) {
      int bit = bit_buffer.front();
      bit_buffer.pop();
      if (bit) bit_set(output, BIT(i));
      else bit_clear(output, BIT(i));
    }
    // Individually write chars in file
    os.write(&output,sizeof(char));
  }
  //????????
  //Last bits???
  //????????
}
vector<bool> char2bits (char c) {
  bitset<8> bit_c (c);
  vector<bool> bool_c;
  for (int i=7; i>=0; i--) {
    bool_c.push_back(bit_c[i]);
  }
  return bool_c;
}

位填充的一种方法是用10...0填充。

01被填充到01100000

解码时,忽略最后一个1后面的所有内容。

如果最后有一个完整的字节,则用10000000填充。

我也会使用header,但对于一组有效负载字节。我的意思是:

HH PP PP PP PP PP PP ..
HH PP PP
  • 如果HH == 256,好的,你有32位有效载荷,然后你会发现另一块
  • If HH <256,你必须读取下一个int(HH/8)字节,并在最后一个HH % 8位。另外,这意味着文件已经结束。

对于大位字段,可以将报头增加到16位或32位。