2

Possible Duplicate:
Detecting endianness programmatically in a C++ program
C Macro definition to determine big endian or little endian machine?

Currently, I have the following function to detect the system endianness :

inline bool detectSystemEndianness()
{
    int i = 1;
    char *c = reinterpret_cast<char*>(&i);
    return (c[0] != i);
}

It returns false if little endian, true if big endian. First question : is this function ok ?

Second question : Instead of this function, I would like to initialize a static variable :

static bool _systemEndianness = /* SOMETHING */

How to do that ? (it has to be done at execution-time and not at compile-time ... at least I think so)

Community
  • 1
  • 1
Vincent
  • 57,703
  • 61
  • 205
  • 388

1 Answers1

0

2 ways

1) Have a preprocessor you define for various platforms so you can act on various endianness at compile time instead of runtime (significantly faster but harder to implement without knowing all platforms

2) similar to your function:

inline bool isLittleEndian()
{
    static const int i = 1;
    static const char* const c = reinterpret_cast<const char* const>(&i);
    return (*c == 1);
}
...
static const bool _systemEndianness = isLittleEndian ();
cppguy
  • 3,611
  • 2
  • 21
  • 36