读取包含C++
我正在尝试使用stringstream
来读取序列化数据的十六进制表示,我可以从数据库或文件中获得,例如“ 11007b000000 ...”,因此,如果我调用称为的函数, readShort
前4个字符被解释为简短,那么如果我称为readInteger
其余8个字符的函数,则为int等。到目前为止输出。 这是我的测试代码:
#include <iostream>
#include <sstream>
int main()
{
std::string baseString = "11007B0000003A0400000A";
std::stringstream baseStream(baseString);
std::stringstream binaryStream(baseString, std::stringstream::out | std::stringstream::in | std::stringstream::binary);
signed short result;
// First attempt
baseStream >> std::hex >> result;
std::cout << result << std::endl;
result = 0;
binaryStream >> std::hex >> result;
std::cout << result << std::endl;
// Second Attempt
baseStream.seekg(0, baseStream.beg);
binaryStream.seekg(0, binaryStream.beg);
result = 0;
baseStream.read((char*)&result, sizeof(result));
std::cout.write((const char*)&result, sizeof(result));
result = 0;
binaryStream.read((char*)&result, sizeof(result));
std::cout.write((const char*)&result, sizeof(result));
// Third attempt
result = 0;
baseStream >> result;
std::cout << result;
result = 0;
binaryStream >> result;
std::cout << result;
}
有更好的方法还是我缺少一些东西?
I am trying to use a stringstream
to read through hex representation of serialized data which I can get from a DB or a file, eg "11007B000000..." so if I call a function called ReadShort
the first 4 characters are interpreted as a short, then if I call a function called ReadInteger
the remaining 8 characters as int, and so on. As of now I've tried istream
, load a fstream
from memory, opening stringstrem
in binary mode, but I can't get the desired output.
This is my test code:
#include <iostream>
#include <sstream>
int main()
{
std::string baseString = "11007B0000003A0400000A";
std::stringstream baseStream(baseString);
std::stringstream binaryStream(baseString, std::stringstream::out | std::stringstream::in | std::stringstream::binary);
signed short result;
// First attempt
baseStream >> std::hex >> result;
std::cout << result << std::endl;
result = 0;
binaryStream >> std::hex >> result;
std::cout << result << std::endl;
// Second Attempt
baseStream.seekg(0, baseStream.beg);
binaryStream.seekg(0, binaryStream.beg);
result = 0;
baseStream.read((char*)&result, sizeof(result));
std::cout.write((const char*)&result, sizeof(result));
result = 0;
binaryStream.read((char*)&result, sizeof(result));
std::cout.write((const char*)&result, sizeof(result));
// Third attempt
result = 0;
baseStream >> result;
std::cout << result;
result = 0;
binaryStream >> result;
std::cout << result;
}
Is there a better approach or is there something I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论