In principle, you can go through the struct and call htonl
or htons
on each uint32_t
or uint16_t
field, respectively, assigning the results back or to a copy of the struct. However, I would not recommend this sort of approach. It's very fragile and subject to struct alignment issues, etc.
Unless transmitting and receiving data is extremely performance-critical, I would simply implement proper serialize and deserialize methods for your structures. You can write numeric values out one byte at a time in binary format, choosing whether you want to write to least significant or most significant part first. But really, I would recommend choosing a modern text-based serialization format like json or (uhg, I hate to say this) xml. The cost of serializing and deserializing text is quite small, and the advantages in terms of debugging ease and extensibility are significant.
Finally, if you want to use text but find json or xml too distasteful, too heavy, or too much of a learning curve, you can always just use printf
and scanf
formatting to read and write structures as text in a fixed order. Writing all numeric values, including floats, in hex rather than decimal will probably improve performance a bit and ensure round-trip accuracy of floating point values. If you don't have C99, another option for floats could be to decompose them to mantissa/exponent form and recompose them using frexp
and ldexp
.