Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file by bits c++

Tags:

c++

ifstream

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.

like image 716
Pastx Avatar asked Mar 13 '14 20:03

Pastx


People also ask

What is fread() in C?

The fread() function reads up to count items of size length from the input stream and stores them in the given buffer. The position in the file increases by the number of bytes read.

How do I read one byte file at a time?

If you want to read one byte at a time, call fread(&buffer, 1, 1, file); (See fread). But a simpler solution will be to declare an array of bytes, read it all together and process it after that. buffer is of type unsigned int.

How do you read a single bit?

To read a bit at a specific position, you must mask out all other bits in the value. The operator that assists in that process is the bitwise & (and). After you mask out all the other bits, the value that remains is either zero or some other value.


1 Answers

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);
}
like image 82
HolyBlackCat Avatar answered Sep 29 '22 16:09

HolyBlackCat