首页 > 其他 > 详细

判断大小端

时间:2021-09-13 16:57:58      阅读:13      评论:0      收藏:0      [点我收藏+]

1. 编译时判断

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

#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. 运行时判断

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

libhv中的

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

判断大小端

原文:https://www.cnblogs.com/suntus/p/15260570.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!