4

I have a C++ application where I need to read a portion of a binary file and put those bytes into a std::bitset.

I am able to read the correct portion of the binary file into a std::string object, but I don't want to go from unsigned char->std::string->std::bitset if I can avoid it.

Is there a way to directly read a portion of the file into a bitset?

So far I have the code (in this example, I'm starting at position 64, then reading 128 bytes into a string, and then initializing a bitset):

//Open the file
std::ifstream file (path, std::ios::in | std::ios::binary | std::ios::ate);

//Move to the position to start reading
file.seekg(64); 

//Read 128 bytes of the file
std::vector<unsigned char> mDataBuffer;
mDataBuffer.resize( 128 ) ;
file.read( (char*)( &mDataBuffer[0]), 128 ) ;

//Read as string (I'm trying to avoid this)
std::string s_data( mDataBuffer.begin(), mDataBuffer.end()); 
std::bitset<1024> foo (s_data); //8 bits/byte x 128 bytes = 1024 bits

file.close()
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
Brett
  • 11,637
  • 34
  • 127
  • 213
  • 2
    Why use the `std::ios::ate` flag when you immediately seek to an absolute position? Also, using the `ate` flag for an input stream doesn't really make much sense as if you don't seek away from the end there's nothing to read. – Some programmer dude Jan 29 '14 at 14:05
  • It's a damn shame, but I can't find anything in the reference that would allow that. – Bartek Banachewicz Jan 29 '14 at 14:05
  • @JoachimPileborg In the larger picture, this code is inside a loop where I do move around the file. That said, I grabbed `ios:ate` from an example somewhere so it very well could be used incorrectly (I'm not really sure how to use it). – Brett Jan 29 '14 at 14:07

1 Answers1

0

As I read the documentation of bit set<>, the string is expected to contain just '1' and '0's. So in your case, just iterate over all bits in your mDataBuffer and use set to set a bit in the bit set.

And of cause, you could stick with the vector< unsigned char > and pull the bits out, if you need them. That makes sense, if you just need to access a few bits.

Torsten Robitzki
  • 3,041
  • 1
  • 21
  • 35