考虑一个16位的整数,它由2个字节组成。内存中存储这两个字节有两种方法:一种是将低字节存储在起始地址,这称为小端字节序;另一种方法是将高序字节存储在起始地址,这称为大端字节序。下面的程序可以检测是大端存储还是小端存储:
#include <stdio.h>
int main(int argc, char *argv[])
{
union
{
unsigned short num;
unsigned char arr[sizeof(short)];
}test;
test.num = 0x0102;
if (sizeof(short) == 2)
{
if (test.arr[0] == 1 && test.arr[1] == 2)
printf("big endian\n");
else if (test.arr[0] == 2 && test.arr[1] == 1)
printf("little endian\n");
else
printf("unknown\n");
}
else
printf("sizeof(short) = %d\n",sizeof(short));
exit(0);
}