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?