What are you doing? Bitfields aren't portable, and unions are generally problematic.

07-07-2012

antred

Yeah, are you even certain an unsigned int will always be 4 bytes on any system you need to run on?

07-08-2012

Tropod

Is there more to this code?
WordByte vs Wordbyte

07-08-2012

dwks

Some points you may find useful:

C (in C99) and C++ (in C++11) introduced a header called <stdint.h> or, C++-style, <cstdint>. This defines uint32_t, int16_t and other types you may find very useful. Of course, you may not want to make your code C++11 dependent (although in practice most compilers will have stdint anyway to support C); in that case I suggest you define your own. For example:

In many projects with more sophisticated build-systems it is the build system's job to figure out details like endianness and bit-sizes, and define types appropriately. (See e.g. cmake.)

Although your code seems to work as it should (i.e. sizeof(WordByte) is 4), compilers are allowed to pad structures. It may not happen in this case because the struct is already a "nice" size, but certainly at higher optimization levels the compiler may well make every struct member aligned to a 16-byte boundary or whatever, and that will break your code completely. I know of one compiler that would align data structures and loops (with padding or no-ops) to 32-byte boundaries at high opt levels because of sophisticated caching requirements.

Often you can hide endianness issues quite easily without resorting to structs. For example, in network programming you'd use htonl() to convert "host" to "network" byte order, and ntohl() to convert the other way (networks use big endian, these functions/macros are no-ops on big-endian processors and do reversing on little endian machines). Or you may be able to inline the differences -- often the only endian-dependent code in my SDL programs is this: