#include <stdio.h>
union myunion{
int a;
char b;
};
int main()
{
// 方法一,联合体
myunion d;
d.a=0x12345678;
printf("0x%x\n",d.b);
if(d.b==0x78)
{
printf("小端\n");
} else if(d.b==0x12)
{
printf("大端\n");
}
//方法二,强制类型转换
int a=0x12345678;
char *p=(char *)&a;
printf("0x%x\n",*p);
if(*p==0x78)
{
printf("小端\n");
} else if(*p==0x12)
{
printf("大端\n");
}
}
/Users/caochenghua/CLionProjects/NavInfo/cmake-build-debug/NavInfo
0x78
小端
0x78
小端
Process finished with exit code 0
Big-Endian: 低地址存放高位,如下:
高地址
---------------
buf[3] (0x78) -- 低位
buf[2] (0x56)
buf[1] (0x34)
buf[0] (0x12) -- 高位
---------------
低地址
Little-Endian: 低地址存放低位,如下:
高地址
---------------
buf[3] (0x12) -- 高位
buf[2] (0x34)
buf[1] (0x56)
buf[0] (0x78) -- 低位
--------------