を使用しstringstream
てバイナリデータを読み取っています。今のところ、クラスに慣れるためにダミーのプログラムを書いているだけです。これが私のプログラムです:
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;
string bytes2hex(char* bytes, int n){
stringstream out;
for (int i = 0;i < n;i++){
out << setfill ('0') << setw(2) << hex << (int) bytes[i] << " ";
}
string st = out.str();
for(short k = 0; k < st.length(); k++)
{
st[k] = toupper(st[k]);
}
return st;
}
int main(){
stringstream ss;
ss << "hello the\0re my\0\0\0 friend";
while (ss.peek() != EOF){
char buf [2];
ss.get(buf, 3);
cout << buf << "\t==>\t" << bytes2hex(buf, 2) << endl;
}
}
出力:
he ==> 68 65
ll ==> 6C 6C
o ==> 6F 20
th ==> 74 68
e ==> 65 00
==> 00 00
これについて 2 つの質問があります。
- を実行するとき
ss.get()
、一度に 2 文字ずつストリームを読み取るために、2 ではなく 3 を入力しなければならないのはなぜですか? - 最初のヌル文字で終了するのはなぜですか? また、それを防ぐにはどうすればよいですか?