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?
Broadly speaking, the endianness in use is determined by the CPU. Because there are a number of options, it is unsurprising that different semiconductor vendors have chosen different endianness for their CPUs.
We can also check the endianness of the machine using the union. We need to create a union that has an integer variable and an array of 4 characters. If the first element (au8DataBuff [0]) of the character array is equal to the LSB Bytes of integer, then the system will be little endian otherwise big-endian.
In very simplified terms, a CPU's endianness refers to the order in which sequential bytes are stored. There are two main types, Big-Endian (most important part of sequence is stored first) and Little-Endian (most important part of sequence is stored last).
Again, endian-ness does not matter if you have a single byte. If you have one byte, it's the only data you read so there's only one way to interpret it (again, because computers agree on what a byte is). Now suppose we have our 4 bytes (W X Y Z) stored the same way on a big-and little-endian machine.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With