Read file by bits c++

18,801

You can't just read file bit by bit. 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);
}
Share:
18,801
Pastx
Author by

Pastx

Updated on August 19, 2022

Comments

  • Pastx
    Pastx over 1 year

    i have binary file as input and i need to read it simple by bits. If i wanted to read file by characters i would use this:

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

    Output of this code is sequence of characters, what i need is sequence of 1 and 0. Function get() return next character and i could not find any ifstream function that would return next bit.

    Is there any similar way how to achieve it ?

    Thank anyone for help.