Search code examples
c++clinuxvisual-c++endianness

Big Endian and Little Endian support for byte ordering


We need to support 3 hardware platforms - Windows (little Endian) and Linux Embedded (big and little Endian). Our data stream is dependent on the machine it uses and the data needs to be broken into bit fields.

I would like to write a single macro (if possible) to abstract away the detail. On Linux I can use bswap_16/bswap_32/bswap_64 for Little Endian conversions.

However, I can't find this in my Visual C++ includes.

Is there a generic built-in for both platforms (Windows and Linux)?

If not, then what can I use in Visual C++ to do byte swapping (other than writing it myself - hoping some machine optimized built-in)?

Thanks.


Solution

  • 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'.