Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 248
user626201 Avatar asked Oct 18 '12 17:10

user626201


2 Answers

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.

like image 35
user1277476 Avatar answered Oct 03 '22 23:10

user1277476


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

like image 91
alk Avatar answered Oct 03 '22 22:10

alk