Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding endian-ness programmatically at compile-time using C++11

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?

like image 356
iammilind Avatar asked Sep 29 '16 07:09

iammilind


People also ask

How do you find endian?

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.

How do you check endianness of a computer?

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.

What is endianness C?

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.

How do you check if a number is big endian or little endian?

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.


1 Answers

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

like image 108
Ruslan Avatar answered Sep 18 '22 18:09

Ruslan