UNIX网络编程卷1(第三版)字节排序函数测试

内存中存储多字节有两种方法,即小端字节序和大端字节序Ubuntu10.04是小端字节序,网际协议所用的字节序为大端字节序

内存地址增长方向:  低序字节->高序字节  小端字节序

                   高序字节->低序字节  大端字节序


主机和网络字节序转换函数在头文件<netinet/in.h>中,函数分别为:

uint16_t htons(uint16_t)

uint32_t htonl(uint32_t)

uint16_t ntohs(uint16_t)

uint32_t ntohl(uint32_t)

命名规则为: h-host,n-network,s-short,l-long, to 即变换到

测试程序为 byteorder_convert_fun1.cpp:

#include <iostream>
#include <iomanip>
#include <netinet/in.h>
using std::cin;
using std::cout;
using std::endl;
using std::hex;

typedef	unsigned short int uint16_t;
typedef unsigned int uint32_t;

int main(int argc, char **argv)
{
	uint16_t c1,d1;
	uint32_t c2,d2;
	c1 = 0x1A2B;
	c2 = 0x1A2B3C4D;
	cout<<hex<<c1<<'\t'<<"htons(c1) = "<<htons(c1)<<endl;
	cout<<hex<<c2<<'\t'<<"htonl(c2) = "<<htonl(c2)<<endl;

	d1 = 0x3E4F;
	d2 = 0x3E4F5A6B;
        cout<<hex<<d1<<'\t'<<"ntohs(d1) = "<<ntohs(d1)<<endl;
        cout<<hex<<c2<<'\t'<<"ntohl(d2) = "<<ntohl(d2)<<endl;


	return 0;
}


root@gujinjin-desktop:/home/gujinjin/Socket# ./byteorder_convert_fun1 
1a2b      htons(c1) = 2b1a
1a2b3c4d  htonl(c2) = 4d3c2b1a
3e4f      ntohs(d1) = 4f3e
3e4f5a6b  ntohl(d2) = 6b5a4f3e

说明:

程序中用typedef 重新定义了 uint16_t 和 uint32_t, 也可以不用定义直接包含头文件 <sys/types.h> 






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值