C语言利用联合体判断大小端

#include

#define   SIZE(a) (sizeof(a)) 
union 
{
    /* data */
    short s;
    char c[SIZE(short)];
    short b;
    int d;
    char f;
}un;
int main(int argc,char **argv)
{
    un.s = 0x0102;
    if(SIZE(short) == 2)//表示short是16位
    {
        printf("===\n");
        printf("c[0] = %d,c[1] = %d\n",un.c[0],un.c[1]);
        if(un.c[0] == 1 && un.c[1] == 2)
            printf("this is big-endian\n");
        else
            printf("this is little-endian\n");
        
        printf("un.b = %d\n",un.b);
        printf("sizeof(un) = %ld\n",SIZE(un));
    }
    else
    {
        printf("--\n");
    } 
    return 0;
}

在这里插入图片描述

你可能感兴趣的:(c语言,c语言,开发语言)