C问题---网络字节序问题

-------------------------------------
典型例题19:C问题---网络字节序问题。
-------------------------------------
 1    #include <stdio.h>
 2    #include <netinet/in.h>
 3    /*
 4     ****************************************************
 5     *htonl 把0x01 的内存的内容按照大端来解释为0x01000000
 6     *联合体中元素地址都是同一个地址,只是解释的方式不同,一个是
 7     *long ,另外一个是short;联合体大小总体是long 大小;
 8     ****************************************************
 9     */
10    union tst{
11        long t;
12        short s;
13    }ts;
14   
15    int  myhtonl(int val) 
16    { 
17        return (int)(htons((short)val)<<16) + htons(val>>16); 
18    }
19   
20    int main(int argc, char * argv[])
21    {
22        int a = 0x12345678;
23        int b = htonl(a);
24        ts.t =0x12345678;
25        printf("1:%.8x/n",b);
26        printf("2:%.8x/n",myhtonl(a));
27        printf("%.8x/n",(short) a);
28        printf("%.8x/n",htons((short)a)<<16);
29        printf("%.8x/n",ntohl(b));
30        printf("%.8x/n",ts.s);
31        return 0;
32    }
-------------------------------
$ ./a.out
1:78563412
2:78563412
00005678
78560000
12345678
00005678
-------------------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值