How to write endian agnostic C/C++ code?

d33tah picture d33tah · Dec 21, 2012 · Viewed 19.2k times · Source

I did some googling and couldn't find any good article on this question. What should I watch out for when implementing an app that I want to be endian-agnostic?

Answer

Carl Norum picture Carl Norum · Dec 21, 2012

The only time you have to care about endianness is when you're transferring endian-sensitive binary data (that is, not text) between systems that might not have the same endianness. The normal solution is to use "network byte order" (AKA big-endian) to transfer data, and then swizzle the bytes if necessary on the other end.

To convert from host to network byte order, use htons(3) and htonl(3). To convert back, use ntohl(3) and ntohs(3). Check out the man page for everything you need to know. For 64-bit data, this question and answer will be helpful.