简体   繁体   中英

C++ - read part of a binary file into a bitset

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM