How to properly serialize raw binary data in C/C++?
16:51 23 Mar 2026

What is the preferred way to serialize data to raw byte array? (Without any serializatuon libs). I though these variants:

  1. #pragma (pack,1) struct A{...} #pragma (pop) or __attribute((packed))__ This variant allows to just memcpy entire struct into byte array, but has great flaw of unaligned accsess to it's fields, wich is slow and will have compatability issues between architectures.

  2. Manually memcpy every field of struct with corresponding offsets to byte array. This doesn't mess with unaligned accsess at all. But looks very ugly.

    Wich way is preferred? Especially in terms of performance and stability.

    P.S. also would be helpful to see advices on deserialization.

c++ c serialization padding memory-alignment