判断主机字节

 1 union 
 2 {
 3 short s;
 4 char c[sizeof(short)];
 5 }test;
 6 
 7 int main()
 8 {
 9 //method 1
10 int a = 0x12345678;
11 if(*((char *)&a) == 0x12)
12 printf("big-endian\n");
13 else
14 printf("little-endian\n");
15 
16 //method 2
17 test.s = 0x0102;
18 if(sizeof(short) == 2)
19 {
20 if(test.c[0] == 1 && test.c[1] == 2)
21 printf("big-endian\n");
22 else
23 printf("little-endian\n");
24 }
25 return 0;
26 }

 

posted @ 2018-11-24 19:44  执著的追求  阅读(104)  评论(0编辑  收藏  举报