Junior — Middle
What ways do you know for converting objects into a byte sequence or other format for transmission or storage?
sobes.tech AI
Answer from AI
Object serialization into a byte sequence or another format for transmission or storage is called serialization. In C/C++, several methods are used for this:
- Manual serialization: independently writing the fields of a structure or class into a buffer, considering alignment and byte order.
- Using standard functions: for example,
memcpyfor copying data into a byte array. - Binary formats: such as Protocol Buffers, FlatBuffers, which provide convenient APIs for serialization and deserialization.
- Text formats: JSON, XML — converting an object into a string representation.
An example of simple manual serialization of a structure in C++:
struct Point {
int x;
int y;
};
void serialize(const Point& p, char* buffer) {
memcpy(buffer, &p.x, sizeof(int));
memcpy(buffer + sizeof(int), &p.y, sizeof(int));
}
void deserialize(const char* buffer, Point& p) {
memcpy(&p.x, buffer, sizeof(int));
memcpy(&p.y, buffer + sizeof(int), sizeof(int));
}
It is important to consider byte order (endianness) and alignment when transmitting between different systems.