0%

判断大小端

1. 编译时判断

编译器没有统一的定义来区分大小端,只能限制一些特定环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN || \
defined(__BIG_ENDIAN__) || \
defined(__ARMEB__) || \
defined(__THUMBEB__) || \
defined(__AARCH64EB__) || \
defined(_MIBSEB) || defined(__MIBSEB) || defined(__MIBSEB__)
// It's a big-endian target architecture
#elif defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \
defined(__LITTLE_ENDIAN__) || \
defined(__ARMEL__) || \
defined(__THUMBEL__) || \
defined(__AARCH64EL__) || \
defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__)
// It's a little-endian target architecture
#else
#error "I don't know what architecture this is!"
#endif

2. 运行时判断

1
2
3
4
5
6
bool isLittleEndian()
{
short int number = 0x1;
char *numPtr = (char*)&number;
return (numPtr[0] == 1);
}

libhv中的

1
2
3
4
5
6
7
8
9
10
11
static inline int detect_endian() {
union {
char c;
short s;
} u;
u.s = 0x1122;
if (u.c == 0x11) {
return BIG_ENDIAN;
}
return LITTLE_ENDIAN;
}

3. 参考

  1. https://stackoverflow.com/a/27054190
  2. https://stackoverflow.com/a/4240014