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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With