将二进制文件读取到 std::vector<bool>
Reading Binary file into std::vector<bool>
您好,我正在尝试将 std::vector 中的 8 位写入二进制文件并将它们读回。编写工作正常,已使用二进制编辑器检查并且所有值都是正确的,但是一旦我尝试阅读,我得到了错误的数据。我正在写入的数据:
11000111 //bits
我从阅读中获得的数据:
11111111 //bits
读取功能:
std::vector<bool> Read()
{
std::vector<bool> map;
std::ifstream fin("test.bin", std::ios::binary);
int size = 8 / 8.0f;
char * buffer = new char[size];
fin.read(buffer, size);
fin.close();
for (int i = 0; i < size; i++)
{
for (int id = 0; id < 8; id++)
{
map.emplace_back(buffer[i] << id);
}
}
delete[] buffer;
return map;
}
写函数(只是为了让你们知道更多发生了什么)
void Write(std::vector<bool>& map)
{
std::ofstream fout("test.bin", std::ios::binary);
char byte = 0;
int byte_index = 0;
for (size_t i = 0; i < map.size(); i++)
{
if (map[i])
{
byte |= (1 << byte_index);
}
byte_index++;
if (byte_index > 7)
{
byte_index = 0;
fout.write(&byte, sizeof(byte));
}
}
fout.close();
}
你的代码在 8 个布尔值上展开一个字节(buffer[i]
的值,其中i
总是0
)。由于您只读取一个恰好为非零的字节,因此您现在最终得到 8 true
秒(因为任何非零整数都转换为 true
)。
您可能希望将一个值拆分为其组成位,而不是分散一个值:
for (int id = 0; id < 8; id++)
{
map.emplace_back((static_cast<unsigned char>(buffer[i]) & (1U << id)) >> id);
}
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 将二进制文件读取到 std::vector<bool>
- 如何在二进制文件中转储 std::vector<bool>?
- 将二进制文件读入位集或向量<bool>