#include<stdio.h>
int main()
{
int a=1;
char *p=(char *)&a;
if(*p==1)
{
printf("小端模式\n");
}
else
{
printf("大端模式\n");
}
return 0;
}
当初没有理解这段代码的原因是没有看懂为什么要用char型指针,因为char是1字节,int是4字节。我们假设其中一个字节的数据,就能知道另外三个字节的数据了,从而验证猜想。也就是char *p=(char *)&a这句。
当定义了a=1时;如果是小端模式且char *p=(char *)&a指针指向了内存低地址处
0000 0000 | 内存高地址 |
0000 0000 | |
0000 0000 | |
0000 0001 | 内存低地址<—— |
*p=就是把里面的数取出来,因为*p==1,故是小断模式
如果大端模式且char *p=(char *)&a指针指向了内存低地址处
0000 0001 | 内存高地址 |
0000 0000 | |
0000 0000 | |
0000 0000 | 内存低地址<—— |
如果 *p不等于1,就是大端模式。