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

时间:2022-04-25 20:38:49

内存中存储多字节有两种方法,即小端字节序和大端字节序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;

typedefunsigned 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>