// 源代码
#include <stdio.h>
/*
* 2016/9/29 yu liang.
*/
int test_one(void)
{
int i=1;
char *p=(char *)&i;
if(*p==1)
printf("Little_endian\n"); // Little_endian
else
printf("Big_endian\n");
}
int checkCPU()
{
{
union w
{
int a;
char b;
} c;
c.a = 1;
return(c.b ==1); // [little endian]
}
}
/*
* 高字节存储在高地址是小端,高字节存储在低地址是大端
*/
int test_two()
{
int *a = 1; // 内存表示为0x00000001.指向编号为 1 的地址
if ((char*)&a[3] == 1) // &a[3] = &a + 3 = &a + sizeof(int) * 3 = a + 12 ====> 1 + 12 = 0xD, 见 c/array/slipt.c 验证
printf("big\n");
else
printf("small\n");
printf("0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]); // 0x1 0x5 0x9 0xd 0x11 0x15
}
int test_thr()
{
union _test
{
int a;
short b;
}test;
test.a = 0x12345678;
if(test.b == 0x1234)
printf("big\n");
if(test.b == 0x5678)
printf("small\n");
}
typedef unsigned char BYTE;
int test_four()
{
unsigned int num,*p;
p = #
num = 0;
*(BYTE *)p = 0xff;
if(num == 0xff) {
printf("The endian of cpu is little\n");
}
else { // num == 0xff000000
printf("The endian of cpu is big\n");
}
return 0;
}
int main(void)
{
int ret = -1;
test_one();
ret = checkCPU();
if (ret == 1)
printf("[little endian]\n"); // [little endian]
else if (ret == 0)
printf("[big endian]\n");
test_two(); // small
test_thr(); // small
test_four(); // The endian of cpu is little
return 0;
}