大端序 (big endian ):最高有效字节存储在最低低至,随地址升高,字节的权重降低。
小端序(little endian): 最低有效字节存储在最低地址,随地址升高,字节的权重升高。
比如说一个int型数字a为0x1234,那么0x12代表a的高位,0x34代表a的低位(类似十进制里面百是高位,十是低位)
计算机的数据存储是以字节为单位的,因此0x12和0x34分别代表两个字节
假设内存地址从左到右是低位到高位
对于小端在内存中的存储为: 3412(低地址存储低位)
对于大端在内存中的存储为:1234(低地址存储高位)
对比发现大端的存储跟书写方式是一致的。
见下表:
字节 | 0 | 1 | 2 | 3 | 类型 |
小端 | 0-7 | 8-15 | 16-23 | 24-32 | int |
大端 | 24-32 | 16-23 | 8-15 | 0-7 | int |
C测试代码:
#include <stdio.h>
union test
{
int a;
char b;
}test;
int main(void)
{
test.a = 1;
if(1 == test.b)
{
printf("little endian!\n");
}
else
{
printf("big endian!\n");
}
return 0;
}
~
巧妙运用联合体共用同一内存来进行测试!