Just a couple points:
- Endian-ness is not generally based on the Operating System but on the processor. For example, Intel x86 processors are little-endian regardless of it running Windows or Linux.
- Your code will always return
HL_LITTLE_ENDIAN
. Why? Because ifstatic constexpr uint8_t endianValues[4] = {0, 1, 2, 3};
then
endianValues[0] == 0
will always be true! Suppose you hadchar x[4] = {'c','o','d', 'e'};
then don't you think it would be shocking ifx[0] == 'e'
instead ofx[0] == 'c'
?The standard way is to use a union. Something like this:
union endian_tester { uint32_t n; uint8_t p[4]; }; const endian_tester sample = {0x01020304}; // this initializes .n constexpr hl_endianness getEndianOrder() { return (0x04 == sample.p[0]) // If Little Endian Byte Order, ? HL_LITTLE_ENDIAN : (0x01 == sample.p[0]) // Else if Big Endian Byte Order, ? HL_BIG_ENDIAN : (0x02 == sample.p[0]) // Else if PDP Endian Byte Order, ...(etc)...
Be aware that constexpr isn't fully supported in my version of Visual Studio 2013 Express
- Not clear to me why you need to use fancy values for HL_LITTLE_ENDIAN, HL_BIG_ENDIAN, etc. You can use 1, 2, etc instead of 0x03020100, 0x00010203, etc.
- A related question answered in stackoverflow (Detecting endianness programmatically in a C++ program)