Skip to content

Instantly share code, notes, and snippets.

@detomon
Created May 18, 2016 09:48
Show Gist options
  • Save detomon/1c07c1c3df021acd54337ad9276b72a3 to your computer and use it in GitHub Desktop.
Save detomon/1c07c1c3df021acd54337ad9276b72a3 to your computer and use it in GitHub Desktop.
Check the system endianness at compile time with C++
#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;
}
@j6t
Copy link

j6t commented Aug 14, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment