C: 判断大小端

2018-09-03  本文已影响8人  赵伯舟

大端与小端

大端与小端指的是多字节的数值在内存中的存储形式,数值的起始存储在内存的高序地址则为大端,反之为小端:


“大端小端”示意图

使用C程序进行判断

#include <stdio.h>
#include <cstdlib>

int main(int argc, char **argv)
{
    union
    {
        short  s;
        char   c[sizeof(short)];
    } un;

    un.s = 0x0102;

    if (sizeof(short) == 2)
    {
        if (un.c[0] == 1 && un.c[1] == 2)
            printf("big-endian\n");
        else if (un.c[0] == 2 && un.c[1] == 1)
            printf("little-endian\n");
        else
            printf("unknown\n");
    } else
        printf("sizeof(short) = %d\n", sizeof(short));

    exit(0);
}

通过union的内存共享机制对un进行赋值,然后判断数组c内容的数值来判断大小端

上一篇 下一篇

猜你喜欢

热点阅读