I want serialize object to binary file using operator “<<“, but
when I serialize, for example, int fields, I obtained it’s symbolic representation:
ofstream out("file", ios::out | ios::binary);
int i=0xAA;
out << i;
And output:
0x31 0x37 0x30
i.e. (0xAA -> 170)
170
If I use write function, all ok:
out.write((char*)&i,sizeof(int));
Output:
0xAA 0x00 0x00 0x00
But can I use << instead write function, to serialize object?
Like:
out << obj.field1 << obj.field2; // etc.
First, a warning: You do know that the bytes within an int, or anything similar, depends on your compiler, computer, and operating system, right? Other systems might output bytes
0x00 0x00 0x00 0xAAfor your example above, or something else entirely. Which means that if you send those bytes to a different computer and attempt to read them, you won’t necessarily get your original int back.Anyway. If you just want to spit out entire objects, one way to set this up would be to just define serialization for your class(es) and/or struct(s) by overloading
operator<<: