大端模式,是指数据的高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中。
小端模式,是指数据的高字节保存在内存的高地址中,而数据的低字节保存在内存的低地址中。
第一种方法思路:
利用指针的强制类型转换,取到低地址
#include <stdio.h>
int main()
{
int a;
a = 0x12345678;
char *p = (char *)&a; //强制转换取到a的低地址
printf("a 的值 0x%x, 地址 %p\n",a,&a);
printf("p 的值 0x%x, 地址 %p\n",*p,p);
printf("p+1的值 0x%x, 地址 %p\n",*(p+1),p+1);
printf("p+2的值 0x%x, 地址 %p\n",*(p+2),p+2);
printf("p+3的值 0x%x, 地址 %p\n",*(p+3),p+3);
/*******************************************
* a 的值 0x12345678, 地址 0x7ffef061833c
* p 的值 0x78, 地址 0x7ffef061833c
* p+1的值 0x56, 地址 0x7ffef061833d
* p+2的值 0x34, 地址 0x7ffef061833e
* p+3的值 0x12, 地址 0x7ffef061833f
* little endian
*
*******************************************/
if (*p == 0x78) { //低地址 存 低字节数据
printf("little endian\n");
}
else if (*p == 0x12) {
printf("big endian\n");
}
return 0;
}
第二种方法思路:
利用共用体所有数据都从同一地址开始存储,从低位地址开始存储。
#include <stdio.h>
union test_union
{
int a;
char b[4];
} test;
int main()
{
test.a = 0x12345678;
printf("test.a 的值 0x%x, 地址 %p\n",test.a,&test.a); //联合体变量的各个成员都是从 低地址 开始公用的
printf("test.b[0]的值 0x%x, 地址 %p\n",test.b[0],&test.b[0]); //&test.b[0]是test.a的低地址
printf("test.b[1]的值 0x%x, 地址 %p\n",test.b[1],&test.b[1]);
printf("test.b[2]的值 0x%x, 地址 %p\n",test.b[2],&test.b[2]);
printf("test.b[3]的值 0x%x, 地址 %p\n",test.b[3],&test.b[3]);
/*******************************************
* 打印结果:
* test.a 的值 0x12345678, 地址 0x55d37ac0f014
* test.b[0]的值 0x78, 地址 0x55d37ac0f014
* test.b[1]的值 0x56, 地址 0x55d37ac0f015
* test.b[2]的值 0x34, 地址 0x55d37ac0f016
* test.b[3]的值 0x12, 地址 0x55d37ac0f017
* little endian
*
*******************************************/
if (test.b[0] == 0x78) { //test.a的低地址 存储的是0x78
printf("little endian\n");
}
else if (test.b[0] == 0x12){
printf("big endian\n");
}
return 0;
}