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

时间:2017-01-25 20:45:45

标签: c++ c++11

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

1 个答案:

答案 0 :(得分:3)

您的代码在8个bool上展开一个字节(buffer[i]的值,其中i始终为0)。由于您只读取了一个非零的字节,因此您现在最终得到8 true s(因为任何非零整数都会转换为true)。

您可能希望一个值拆分为其组成位,而不是传播一个值:

for (int id = 0; id < 8; id++)
{
    map.emplace_back((static_cast<unsigned char>(buffer[i]) & (1U << id)) >> id);
}
相关问题