Reputation: 13040
I want to be lazy and write some code that will break if the endianness of the target machine is different from my own, for right now. But I would like to know when it breaks of course, so I can fix it if or when it becomes necessary.
Is the endianness of floats and integers a property of the compiled program, such that I can check it at compile time with an assertion somehow? Or would it be something I have to assert at runtime?
Upvotes: 7
Views: 1529
Reputation: 1
Is the endianness of floats and integers a property of the compiled program, such that I can check it at compile time with an assertion somehow?
It's decided at compile time which machine code is generated. A program cannot be compiled to machine code, that works on completely different CPU architectures.
To check at runtime which endianess is used at your current hardware, there are several methods available.
Also see Determining endianness at compile time.
Instead of using assertions for assuming a particular endianess in your code, you should use techniques to make any data saved to files, or communicated over a network connection transparent regarding endianess.
One way to do so, is to specify only big endian data should be used, and the code uses the hton<x>()
, ntoh<x>()
family of functions to encode and decode the data (see also network byte order).
Upvotes: 1
Reputation: 36441
Some hardware provide both (PowerPC for example)... but in general there is a native mode. Anyway, a compile-time assertion is generally sufficient.
Upvotes: 2
Reputation: 225487
Yes, endianness is inherent to the machine in question and is known at compile time. Most OSs will have a #define
set up somewhere to tell you what the endianness is.
On Linux in particular you can do the following:
#if __BYTE_ORDER == __LITTLE_ENDIAN
...
#elif __BYTE_ORDER == __BIG_ENDIAN
...
#elif __BYTE_ORDER == __PDP_ENDIAN
...
#else
...
#endif
Upvotes: 6