Skip to content

Instantly share code, notes, and snippets.

@saswata-dutta
Created September 13, 2023 09:53
Show Gist options
  • Save saswata-dutta/fe2b8a1251bce2b801986b97ab4920ee to your computer and use it in GitHub Desktop.
Save saswata-dutta/fe2b8a1251bce2b801986b97ab4920ee to your computer and use it in GitHub Desktop.
struct X {
unsigned int length;
char *str;
};
std::string serialize(const X &x) {
std::string s;
s.resize(sizeof(x.length) + x.length);
std::memcpy(s.c_str(), &x.length, sizeof(x.length));
std::memcpy(s.c_str() + sizeof(x.length), x.str, x.length);
return s;
}
X deserialize(const std::string &s) {
X x;
std::memcpy(&x.length, s.c_str(), sizeof(x.length));
x.str = new char[x.length];
std::memcpy(x.str, s.c_str() + sizeof(x.length), x.length);
return x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment