Reading file by bit C ++

I have a binary as input, and I just need to read it bit by bit. If I wanted to read a file by character, I would use this:

    ifstream f(inFile, ios::binary | ios::in);
    char c;
    while (f.get(c)) {
        cout << c;
    }

The output of this code is a sequence of characters, I need a sequence of 1 and 0. The get () function returns the next character, and I could not find any ifstream function that would return the next bit.

Is there a similar way how to achieve it?

Thanks to someone for the help.

+4
source share
1 answer

You cannot just read a file in parts. So you should use something like this:

ifstream f(inFile, ios::binary | ios::in);
char c;
while (f.get(c))
{
    for (int i = 7; i >= 0; i--) // or (int i = 0; i < 8; i++)  if you want reverse bit order in bytes
        cout << ((c >> i) & 1);
}
+12
source

Source: https://habr.com/ru/post/1531649/


All Articles