我有20byte二進制char數組。我想分成3個部分:4byte,8byte,8byte。我像下面這樣實現它。它的工作原理,但似乎我可能能夠使用緩衝區流。我想知道如何使用它。將二進制char數組轉換爲stringstream並從緩衝區彈出
現在
void main()
{
// _data is 20byte binary char array. 0000000000000000000000000000000000000000000001111001110001111111001110000010110000001011101101000000000000000000000000000000000000000000000000000000000000000001
// strA (4 byte)
string strA;
for (std::size_t i = 0; i < 4; ++i) {
strA += bitset<8>(_data.c_str()[i]).to_string();
}
cout << strA << endl; // 00000000000000000000000000000000
// strB (8 byte)
string strB;
for (std::size_t i = 4; i < 12; ++i) {
strB += bitset<8>(_data.c_str()[i]).to_string();
}
cout << strB << endl; // 0000000000000111100111000111111100111000001011000000101110110100
// strC (8 byte)
string strC;
for (std::size_t i = 12; i < 20; ++i) {
strC += bitset<8>(_data.c_str()[i]).to_string();
}
cout << strC << endl; // 0000000000000000000000000000000000000000000000000000000000000001
}
期望
我想要實現這樣的。
void main()
{
stringstream ss = _data;
strA = ss.pop(4);
strB = ss.pop(8);
strC = ss.pop(8);
}
更新1
謝謝你們。我正在嘗試你給我的所有答案。我是C++新手,所以需要時間來理解它。以下是Anders K的一個。
struct S { char four[4]; char eight1[8]; char eight2[8]; };
struct S *p = reinterpret_cast<S*>(&_data);
cout << p->four << endl; // => Output "(" I think I can find way to output
更新2
它可以使用字符串:: SUBSTR。謝謝扎基爾。
int main()
{
// I don't know how to change to string value in smart way..
string str;
for (std::size_t i = 0; i < _data.size(); ++i) {
str += bitset<8>(_data.c_str()[i]).to_string();
}
cout << str << endl; // 0000000000000000000000000000000000000000000001111001110001111111001110000010110000001011101101000000000000000000000000000000000000000000000000000000000000000001
std::string d = str; // Your binary stream goes here
int lenA = (4*8); // First 4 Bytes
int lenB = (8*8); // Second 8 Bytes
int lenC = (8*8); // Last 8 Bytes
std::string strA = d.substr(0, lenA);
std::string strB = d.substr(lenA + 1, lenB - 1);
std::string strC = d.substr(lenA + lenB + 1, lenC - 1);
cout << strA << endl; // 00000000000000000000000000000000
cout << strB << endl; // 000000000000111100111000111111100111000001011000000101110110100
cout << strC << endl; // 000000000000000000000000000000000000000000000000000000000000001
}
更新3
當我嘗試雪夫的方式我得到了一個錯誤。這是我的錯,我想我可以解決它。我想我應該重新考慮_data的類型。
int main
{
const char data = _data;
const char *iter = data;
string strA = pop(iter, 4);
string strB = pop(iter, 8);
string strC = pop(iter, 8);
cout << "strA: '" << strA << "'" << endl;
cout << "strB: '" << strB << "'" << endl;
cout << "strC: '" << strC << "'" << endl;
}
使錯誤消息
爲什麼你要使用'stringstream'而不是'string'?並且'void main()'應該是'int main()' – Curious
將它們分組在一個'struct'或'class'中是不是更容易?這些部分必須有一些特定的名稱,以便在分組中使用它更容易。如果你使用'class',你可以包裝內部細節並公開一個很好的界面來訪問這三個部分。 – Azeem
爲什麼不做類似'struct S {char four [4]; char eight1 [8]; char eight2 [8]; }; struct S * p = reinterpret_cast
(&_data [0]); '看起來不像是矯枉過正。 –