Created
July 25, 2014 08:42
-
-
Save mitsu-ksgr/b18feca40f5e4fbccbd6 to your computer and use it in GitHub Desktop.
【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 <iostream> | |
#include <cstdint> | |
/* | |
1. Assigns 1 to 16bit variable. | |
int16_t x16 = 1; | |
BE : 00000000 00000001 | |
LE : 00000001 00000000 | |
2. Cast it to 8bit variable, then get upper 8bits. | |
int8_t x8 = *reinterpret_cast<int8_t*>(&x16); | |
BE : 00000000 | |
LE : 00000001 | |
3. (^_^)b | |
bool is_be = x8 == 0; | |
bool is_le = x8 == 1; | |
//*/ | |
bool isBigEndian() | |
{ | |
int16_t x = 1; | |
return *reinterpret_cast<int8_t*>(&x) == 0; | |
} | |
bool isLittleEndian() | |
{ | |
return !isBigEndian(); | |
} | |
int main() | |
{ | |
std::cout << std::boolalpha; | |
std::cout << "isBigEndian : " << isBigEndian() << std::endl; | |
std::cout << "isLittleEndin : " << isLittleEndian() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment