8

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.

Pastx
  • 687
  • 3
  • 8
  • 23

1 Answers1

21

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);
}
stefaanv
  • 14,072
  • 2
  • 31
  • 53
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207