将二进制文件读取到 std::vector<bool>

Reading Binary file into std::vector<bool>

本文关键字:二进制文件 bool gt lt 读取 std vector      更新时间:2023-10-16

您好,我正在尝试将 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);
}