-------------------------------------
典型例题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
-------------------------------
C问题---网络字节序问题
最新推荐文章于 2021-07-11 19:36:34 发布