如何保存(和检索)文件的位序列
How to save (and retrieve) to file a sequence of bits
我想在一个文件中存储一个比特序列。
我尽量只描述最重要的:
- 我有一个矢量(我知道,不是一个好主意,但我只是简单地使用它)
- 我想把它存储在一个文件(我使用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位。
相关文章:
- Gstreamer:每 5 秒使用多文件墨水保存图像/jpeg
- 可视化C++从文件中保存/读取多个变量
- 在 C++ 的文本文件中保存多个输出
- 如何使用 STL C++读取文件和保存连字符
- 使用 rapidjson 直接在文件中保存 json
- 使用 std::cout 将"\r"写入文件会保存以前覆盖的行
- CPP文件被保存在错误的格式,无法解决它
- 从二进制文件中保存的 4 字节双精度读取 8 字节双精度
- 检查一系列单词,形成一个文本文件,保存在字符串vector C 中
- 如何读取文件并保存特定的发生字符串
- Armadillo:在一个hdf5文件中保存多个数据集
- 在BMP文件中保存屏幕截图的设备上下文
- 如何在文件中保存和加载故事流节点
- 特定文件夹保存和读取
- POCO - 属性文件配置保存方法始终使用 ":" 作为分隔符进行写入
- 我可以从文件中保存和加载C++函数吗?
- 如何在文件中保存/读取数据数组 (C++)
- 读取文件并保存完全相同的文件 c++
- 文件未保存或不保存
- 从文本文件中保存双精度以供以后使用C++