c - Byte swapping a struct -


okay hate ask question ... here goes. writing code in c on x86 machine. want send struct on network , and want convert struct network byte order ... understand drama packing , the gcc packing pragmas ... want know how convert struct (or array or such arbitrary memory blob) network byte order.

is there standard (unix/linux/posix) function call can use or must roll own.

x

in principle, can go through struct , call htonl or htons on each uint32_t or uint16_t field, respectively, assigning results or copy of struct. however, not recommend sort of approach. it's fragile , subject struct alignment issues, etc.

unless transmitting , receiving data extremely performance-critical, implement proper serialize , deserialize methods structures. can write numeric values out 1 byte @ time in binary format, choosing whether want write least significant or significant part first. really, recommend choosing modern text-based serialization format json or (uhg, hate this) xml. cost of serializing , deserializing text quite small, , advantages in terms of debugging ease , extensibility significant.

finally, if want use text find json or xml distasteful, heavy, or of learning curve, can use printf , scanf formatting read , write structures text in fixed order. writing numeric values, including floats, in hex rather decimal improve performance bit , ensure round-trip accuracy of floating point values. if don't have c99, option floats decompose them mantissa/exponent form , recompose them using frexp , ldexp.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -