Big Endian
In big endian, you store the most significant byte in the smallest address. Here's how it would look:
Address | Value |
1000 | 90 |
1001 | AB |
1002 | 12 |
1003 | CD |
Little Endian
In little endian, you store the least significant byte in the smallest address. Here's how it would look:
Address | Value |
1000 | CD |
1001 | 12 |
1002 | AB |
1003 | 90 |
大端字节序:高位字节存在小地址;小端字节序:低位字节存在小地址。
编程确定机器属于大端字节序还是小端字节序
#include <stdio.h>
int
main(int argc, char **argv)
{
union{
short s;
char c[sizeof(short)];
}un;
un.s = 0x0102;
printf("sizeof(un) = %d\n",sizeof(un));
if (sizeof(short) == 2) {
if(un.c[0] == 1 && un.c[1] == 2)
printf("big-endian\n");
else if(un.c[0] == 2 && un.c[1] == 1)
printf("little-endian\n");
else printf("unknow\n");
}
else {
printf("sizeof(short) = %d\n", sizeof(short));
}
return 0;
}