Created
May 18, 2016 09:48
-
-
Save detomon/1c07c1c3df021acd54337ad9276b72a3 to your computer and use it in GitHub Desktop.
Check the system endianness at compile time with C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdint> | |
#include <iostream> | |
struct Endian { | |
constexpr static bool is_big() { | |
union { | |
uint32_t i; | |
uint8_t c[4]; | |
} check = { | |
.i = 0x01000000 | |
}; | |
return check.c[0]; | |
} | |
constexpr static bool is_little() { | |
return !is_big(); | |
} | |
}; | |
int main() { | |
std::cout << "Is big endian: " << Endian::is_big() << std::endl; | |
std::cout << "Is little endian: " << Endian::is_little() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And it has undefined behavior: If you intialize member
.i
of a union, then you can only read.i
, but not.c
. So, if the program prints what you expect, then it is pure luck.