简体   繁体   English

C ++ - 将二进制文件的一部分读入bitset

[英]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 . 我有一个C++应用程序,我需要读取一部分二进制文件并将这些字节放入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. 我能够将二进制文件的正确部分读入std::string对象,但我不想从unsigned char->std::string->std::bitset转到我可以避免它。

Is there a way to directly read a portion of the file into a bitset? 有没有办法直接将文件的一部分读入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 ): 到目前为止我的代码(在本例中,我开始在位置64,然后读出128个字节成string ,然后初始化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. 当我阅读位集<>的文档时,字符串应该只包含'1'和'0'。 So in your case, just iterate over all bits in your mDataBuffer and use set to set a bit in the bit set. 因此,在您的情况下,只需迭代mDataBuffer中的所有位,并使用set在位集中设置一个位。

And of cause, you could stick with the vector< unsigned char > and pull the bits out, if you need them. 因此,你可以坚持使用vector< unsigned char >并将这些位拉出来,如果你需要的话。 That makes sense, if you just need to access a few bits. 这是有道理的,如果你只需要访问几个位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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