計算機字節序問題---字節序編程測試

-------------------------------------
典型例題 25:計算機字節序問題---字節序編程測試
-------------------------------------
 1    /*
 2     * filename: byteorder.c
 3     */
 4   
 5    #include <stdio.h>
 6    #include <netinet/in.h>
 7   
 8    union {
 9        short s;
10        char c[sizeof(short)];
11    }un;
12    short test = 0x0203;
13   
14    void byteorder(char *msg)
15    {
16        printf("%s", msg);
17        if (sizeof(short) == 2) {
18            if (un.c[1] == (test & 0x00ff)) {
19                printf("big-endian/n");
20            }
21            else if (un.c[0] == (test & 0x00ff)) {
22                printf("little-endian/n");
23            }
24            else {
25                printf("unkowned/n");
26            }
27        }
28        else {
29            printf("sizeof(short) = %d/n", sizeof(short));
30        }
31    }
32   
33    int main(void)
34    {
35        char *msg1 = "Host Byte Order: ";
36        ar *msg2 = "Network Byte Order: ";
37   
38        un.s = test;
39        byteorder(msg1);
40        un.s = htons(test);
41        byteorder(msg2);
42   
43        return 0;
44    }
--------------------------
$ ./a.out
Host Byte Order: little-endian
Network Byte Order: big-endian
--------------------------
 1    #include <stdio.h>
 2   
 3    int checkCPU()
 4    {
 5        union w
 6        {
 7            int a;
 8            char b;
 9        }c;
10        c.a=1;
11        return(c.b==1);
12    }
13   
14    int checkparser()
15    {
16        short int x;
17        char x0,x1;
18   
19        x=0x1122;
20        x0=((char*)&x)[0];   //低地址單元
21        x1=((char*)&x)[1];   //高地址單元
22        if (0x11==x0)
23            {
24                printf("big_enddian/n");
25            }else{       
26            printf("little_endian/n");
27        }
28        return 0;
29    }
30   
31    int main ()
32    {
33        int t=checkCPU();
34        if(0==t)
35            printf("big_endian/n");
36        else
37            printf("little_endian/n");
38        checkparser();
39        return 0;    
40   
41    }
--------------------------
$ ./a.out
little_endian
little_endian
--------------------------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章