2

I have objects that I like to be able to serialize as a consecutive stream of bytes. Two questions:

1) Is an array of char appropriate for this task? If not what are better options?

2) What is the most efficient of doing this? So far what I have done is using memcpy. Is it possible to cast/convert a double, for instance, into 8 bytes of chars and vice versa without going through memcpy?

I'm well aware of external libraries for this but I like to learn new stuff.

mmirzadeh
  • 6,893
  • 8
  • 36
  • 47

2 Answers2

1

Serialization implies that you are taking an object and giving it a represntation that can be used to completely rebuild it using only that representation. Usually, serialization applies to file storage, but it is often used to communicate objects over networks.

So, usually, using char or unsigned char works just fine. The real bear of the problem is ensuring that you are storing everything that object contains. That includes objects that are referenced in the object that you are trying to serialize.

I would start by googling "deep copy." deep copy vs shallow copy

Edit: memcpy is a form of "shallow copy."

Community
  • 1
  • 1
Michael McGuire
  • 1,034
  • 9
  • 20
1
  1. Yes, char is a great choice for the task.

  2. memcpy is fine if you are storing your result into a file and reading it again on the same architecture. But if you want to pass it through a socket or open it somewhere else, you have to be more careful. With floating points and integral types, representation and endianess are always an issue.

Don't do a simple memcpy on a float/integer (and avoid even more casting it from a buffer (strict aliasing and UB)).

For floating points, lookup this two functions frexp() and ldexp(). There is a lot of that on the web so there is no point of copying it here.

For integrals, you can do something like this:

buffer[0] = integer >> 24;  
buffer[1] = integer >> 16;  
buffer[2] = integer >> 8;  
buffer[3] = integer;

This guarantees getting the same number back.

imreal
  • 10,178
  • 2
  • 32
  • 48