Big Endian and Little Endian support for byte ordering

On both platforms you have

for short (16bit): htons() and ntohs()

for long (32bit): htonl() and ntohl()

The missing htonll() and ntohll() for long long (64bit) could easily be build from those two. See this implementation for example.

Update-0:

For the example linked above Simon Richter mentions in a comment, that it not necessarily has to work. The reason for this is: The compiler might introduce extra bytes somewhere in the unions used. To work around this the unions need to be packed. The latter might lead to performance loss.

So here's another fail-safe approach to build the *ll functions: https://stackoverflow.com/a/955980/694576

Update-0.1:

From bames53' s comment I tend to conclude the 1st example linked above shall not be used with C++, but with C only.

Update-1:

To achieve the functionality of the *ll functions on Linux this approach might be the ' best'.


Not the same names, but the same functionality does exist.

EDIT: Archived Link -> https://web.archive.org/web/20151207075029/http://msdn.microsoft.com/en-us/library/a3140177(v=vs.80).aspx

_byteswap_uint64, _byteswap_ulong, _byteswap_ushort


htons and htonl (and similar macros) are good if you insist on dealing with byte sex.

However, it's much better to sidestep the issue by outputting your data in ASCII or similar. It takes a little more room, and it transmits over the net a little more slowly, but the simplicity and futureproofing is worth it.

Another option is to numerically take apart your int's and short's. So you & 0xff and divide by 256 repeatedly. This gives a single format on all architectures. But ASCII's still got the edge because it's easier to debug with.