大小端的概念在这里不解释了,我们直接引用一句很经典的话:
大端模式:高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中;
小端模式:高字节保存在内存的高地址中,而数据的低字节保存在内存的低地址中;
但是看这文字解析是很枯燥的,我们来一步步说明。
首先:我们都知道数据在内存的分布,栈是往下增长的,堆是往上增长的。也就是:
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
void print_n(void)
{
int n = 0;
printf("n:%p\n", &n);
}
int main(int argc, char *argv[])
{
printf("-------------------stack---------------\n");
int m = 1;
printf("m:%p\n ", &m);
print_n();
printf("-------------------heap---------------\n");
char *x = malloc(4);
char *y = malloc(4);
printf("x:%p y:%p\n", x, y);
free(x);
free(y);
return 0;
}
输出结果如下:
也就是在我的上述运行中,
可以看到, m比n的内存地址要高, y比x的内存地址要高。这就是我们说的内存地址高低。
接着来看,我们都知道int在内存中占4个字节;比如 int x = 0x12345678,那么在内存中如何存放的呢?
如上图所示:
0x78属于低位,在左边的图中,它存在了低地址,所以这是小端模式;
同理:在右边的图中,0x78存在高地址中,所以这是大端模式;
我们编码验证一下:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int x = 0x12345678;
char *p = (char *)&x;
if(*p = 0x78)
printf("little endian!\n");
else if(*p = 0x12)
printf("big endian!\n");
else
printf("error!\n");
return 0;
}
输出结果如下:
我们可以进一步验证一下,通过都可执行文件头来判断大小端:
Do you understand?