I'm using something like the following. Is there a better way?
for (int i = 0; i < sizeof(Person) ; i++) {
const char &cr = *((char*)personPtr + i);
cout << bitset<CHAR_BIT>(cr);
}
I would suggest to provide a serialize_as_binary
utility in your Person
class.
template<typename T>
void serialize_as_bin(const T &t, ostream& os) {
const unsigned char *p = reinterpret_cast<const unsigned char *>(&t);
for(size_t s = 0; s < sizeof t; ++s, ++p) serialize_as_bin(*p, os);
}
template<>
void serialize_as_bin(const unsigned char &t, ostream& os) {
// Code to serialize one byte
std::bitset<CHAR_BIT> x(t);
os << x;
}
struct Person {
A a;
B b;
ostream& serialize_as_binary(ostream& os) {
serialize_as_bin(a, os);
serialize_as_bin(b, os);
return os;
}
void deserialize_from_binary() {
// Similar stuff if required
...
}
};
Live example here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With