简体   繁体   中英

Reading Binary file into std::vector<bool>

Hello I am trying to write 8 bits from std::vector to binary file and read them back . Writing works fine , have checked with binary editor and all values are correct , but once I try to read I got bad data . Data that i am writing :

11000111 //bits

Data that i got from reading:

11111111 //bits

Read function :

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;
}

Write function(just so you guys know more whats going on)

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();
}

Your code spreads out one byte (the value of buffer[i] , where i is always 0 ) over 8 bools. Since you only read one byte, which happens to be non-zero, you now end up with 8 true s (since any non-zero integer converts to true ).

Instead of spreading one value out, you probably want to split one value into its constituent bits:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM