Avoid technically UB type punning when determining endianness

This commit is contained in:
Martin Hořeňovský 2019-10-27 22:07:10 +01:00
parent 2fbd66c51c
commit 7ada02e21e
No known key found for this signature in database
GPG Key ID: DE48307B8B0D381A
1 changed files with 7 additions and 9 deletions

View File

@ -38,13 +38,11 @@ namespace Detail {
enum Arch { Big, Little }; enum Arch { Big, Little };
static Arch which() { static Arch which() {
union _{ int one = 1;
int asInt; // If the lowest byte we read is non-zero, we can assume
char asChar[sizeof (int)]; // that little endian format is used.
} u; auto value = *reinterpret_cast<char*>(&one);
return value ? Little : Big;
u.asInt = 1;
return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
} }
}; };
} }