In C/C++ usually you would just write a struct
with the various members in the correct order (correct packing may require compiler-specific pragmas) and dump/read it to/from file with a raw fwrite
/fread
(or read
/write
when dealing with C++ streams). Actually, pack
and unpack
were born to read stuff generated with this method.
If you instead need the result in a buffer instead of a file it's even easier, just copy the structure to your buffer with a memcpy
.
If the representation must be portable, your main concerns are is byte ordering and fields packing; the first problem can be solved with the various hton*
functions, while the second one with compiler-specific directives.
In particular, many compilers support the #pragma pack
directive (see here for VC++, here for gcc), that allows you to manage the (unwanted) padding that the compiler may insert in the struct
to have its fields aligned on convenient boundaries.
Keep in mind, however, that on some architectures it's not allowed to access fields of particular types if they are not aligned on their natural boundaries, so in these cases you would probably need to do some manual memcpy
s to copy the raw bytes to variables that are properly aligned.