tags:

views:

124

answers:

2

I have an input stream from a binary file. I want to create a bitset for the first 5 bits of the stream. Here is the code I have so far:

ifstream is;    
is.open ("bin_file.out", ios::binary );

bitset<5> first_five_bits;

is >> first_five_bits; // always is set to default 00000
+1  A: 
char c;
if( ! cin.get(c) ) throw ROFL();  // return error, flip bit, call mom
bitset<5> first_five_bits(c >> (CHAR_BIT-5));  // CHAR_BIT in <climits>
wilhelmtell
Will this populate with the first five bits or bytes?
Jon
First five bytes. If you want the first five bits then bit-manipulate the input.
wilhelmtell
Updated the answer to grab the first five bits. Removed the sample code for grabbing the first five bytes.
wilhelmtell
Thanks! How would this change if the bit endianness was big? I am guessing it would be just first_five_bits(c). Is that correct?
Jon
@Jon: I don't think there is such a thing as bit endianness, eventhough on PPC-registers, they start counting from the msb to the lsb. All systems I know have the msb as first bit. But checking this doesn't harm.
stefaanv
+1  A: 

Streams don't work with bits, so you should read in a byte and set that to the bitset.

Not compiled, not tested:

char c;
is >> c;
bitset<5> first_five_bits(c >> 3);
stefaanv
`operator>>()` formats the input. It will skip whitespace, manipulate the input bits in the case of ASCII numbers etc.
wilhelmtell
@wilhelm agreed: the cin.get(c) from your answer is better here. I mainly wanted to point out that streams work with bytes, not bits.
stefaanv