简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM