网络字节序(Big Endian)

网络字节序(Big Endian)

test.c
-------------------------------------
01 #include <stdio.h>
02 #include <arpa/inet.h>
03
04 int main()
05 {
06     unsigned short name = 0x123;
07     unsigned char * p = (unsigned char *)&name;
08     printf("p[0] = 0x%x\n", p[0]);
09     printf("p[1] = 0x%x\n", p[1]);
10
11     printf("htons(0x%x) = 0x%x\n", name, htons(name));
12
13     name = htons(name);
14     p = (unsigned char *)&name;
15     printf("p[0] = 0x%x\n", p[0]);
16     printf("p[1] = 0x%x\n", p[1]);
17
18     return 0;
19 }


# gcc test.c
# ./a.out
p[0] = 0x23
p[1] = 0x1
htons( 0x123) = 0x2301
p[0] = 0x1
p[1] = 0x23


网络字节序(Big Endian)

起始地址
|------|------|
| 0x 01 | 0x 23 |
|------|------|

X86体系结构(Little Endian)

起始地址
|------|------|
| 0x 23 | 0x 01 |
|------|------|

注: 字节序 not 位序



test.c
-------------------------------------
 01 #include <stdio.h>
02 #include <arpa/inet.h>
03
04 int main()
05 {
06     unsigned int name = 0x01234567;
07     unsigned char * p = (unsigned char *)&name;
08     printf("p[0] = 0x%x\n", p[0]);
09     printf("p[1] = 0x%x\n", p[1]);
10     printf("p[2] = 0x%x\n", p[2]);
11     printf("p[3] = 0x%x\n", p[3]);
12
13     printf("htols(0x%x) = 0x%x\n", name, htonl(name));
14
15     name = htonl(name);
16     p = (unsigned char *)&name;
17     printf("p[0] = 0x%x\n", p[0]);
18     printf("p[1] = 0x%x\n", p[1]);
19     printf("p[2] = 0x%x\n", p[2]);
20     printf("p[3] = 0x%x\n", p[3]);
21
22     return 0;
23 }


# gcc test.c
# ./a.out
p[0] = 0x67
p[1] = 0x45
p[2] = 0x23
p[3] = 0x1
htols(0x1234567) = 0x67452301
p[0] = 0x1
p[1] = 0x23
p[2] = 0x45
p[3] = 0x67


网络字节序(Big Endian)

起始地址
|------|------|------|------|
| 0x 01 | 0x23 | 0x 45 | 0x 67 |
|------|------|------|------|

X86体系结构(Little Endian)

起始地址
|------|------|------|------|
| 0x 67 | 0x 45 | 0x23 | 0x 01 |
|------|------|------|------|



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值