簡體   English   中英

C ++ - 將二進制文件的一部分讀入bitset

[英]C++ - read part of a binary file into a bitset

我有一個C++應用程序,我需要讀取一部分二進制文件並將這些字節放入std::bitset

我能夠將二進制文件的正確部分讀入std::string對象,但我不想從unsigned char->std::string->std::bitset轉到我可以避免它。

有沒有辦法直接將文件的一部分讀入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()

當我閱讀位集<>的文檔時,字符串應該只包含'1'和'0'。 因此,在您的情況下,只需迭代mDataBuffer中的所有位,並使用set在位集中設置一個位。

因此,你可以堅持使用vector< unsigned char >並將這些位拉出來,如果你需要的話。 這是有道理的,如果你只需要訪問幾個位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM