I have referred many questions in SO on this topic, but couldn't find any solution so far. One natural solution was mentioned here: Determining endianness at compile time.
However, the related problems mentioned in the comments & the same answer.
With some modifications, I am able to compile a similar solution with g++ & clang++ (-std=c++11
) without any warning.
static_assert(sizeof(char) == 1, "sizeof(char) != 1");
union U1
{
int i;
char c[sizeof(int)];
};
union U2
{
char c[sizeof(int)];
int i;
};
constexpr U1 u1 = {1};
constexpr U2 u2 = {{1}};
constexpr bool IsLittleEndian ()
{
return u1.i == u2.c[0]; // ignore different type comparison
}
static_assert(IsLittleEndian(), "The machine is BIG endian");
Demo.
Can this be considered a deterministic method to decide the endian-ness or does it miss type-punning or something else?
Determine endianness. Another way to determine endiannes is to use a character pointer to the bytes of an int and then check its first byte to see if it is 0 or 1.
Now if you take a pointer c of type char and assign x 's address to c by casting x to char pointer, then on little endian architecture you will get 0x10 when *c is printed and on big endian architecture you will get 0x76 while printing down *c . Thereby you can find out the endianness for machine.
The endianness refers to the byte order used by your computer or microcontroller or a machine to read or write a single “machine word” in memory (32-bit machine's word size is 32-bit and 64-bit machine's word size is 64-bit ). In other words, The endian will decide how to stores multiple bytes in computer memory.
In little endian machines, last byte of binary representation of the multibyte data-type is stored first. On the other hand, in big endian machines, first byte of binary representation of the multibyte data-type is stored first.
Since C++20 you can use std::endian
from the <type_traits>
header:
#include <type_traits>
int main()
{
static_assert(std::endian::native==std::endian::big,
"Not a big endian platform!");
}
See it live
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