计算机字节序问题---字节序编程测试

-------------------------------------
典型例题 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
--------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值