Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is endianness decided at compile time?

Tags:

c++

c

endianness

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?

like image 331
Anne Quinn Avatar asked Jul 07 '16 15:07

Anne Quinn


People also ask

What determines the endianness?

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.

Is there a quick way to determine endianness of your machine?

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.

What is endianness what part of a microprocessor determines endianness?

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

Does endianness matter for a single byte?

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.


1 Answers

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
like image 106
dbush Avatar answered Oct 14 '22 00:10

dbush