#include <iostream>
#include <stdexcept>
using namespace std;
template<typename U>
bool is_big_endian() {
if (sizeof(U) == sizeof(char)) {
throw std::logic_error( "big endian versus little endian can only be measured for data types with size greater than the sizeof(char)");
}
const int num_bytes = sizeof(U) / sizeof(char);
union {
char bytes[num_bytes];
U x;
} U_byte_mask;
U_byte_mask.x = 1;
if (U_byte_mask.bytes[0] == 1) return false;
if (U_byte_mask.bytes[num_bytes-1] == 1) return true;
throw std::logic_error( "this datatype on this machine is neither big endian nor small endian");
}
int main()
{
bool int_is_bigendian;
try {
int_is_bigendian = is_big_endian<int>();
} catch (exception &e) {
cerr << e.what() << endl;
return 1;
}
bool long_is_bigendian;
try {
long_is_bigendian = is_big_endian<long>();
} catch (exception &e) {
cerr << e.what() << endl;
return 1;
}
if (int_is_bigendian) {
cout << "int's are big endian" << endl;
} else {
cout << "int's are small endian" << endl;
}
if (long_is_bigendian) {
cout << "long's are big endian" << endl;
} else {
cout << "long's are small endian" << endl;
}
return 0;
}