网络编程—常用的基本函数介绍--htonl、ntohl、htons、ntohs

  1. htonl()函数

将主机的unsigned long值转换成为网络字节顺序(32位)(一般这几跟网络上传输的字节顺序是不通的,

分大小端),函数返回一个网络字节顺序的数字。

#include "stdafx.h"

#include<stdio.h>
#include<WinSock2.h>
#pragma comment(lib,"ws2_32.lib")


int _tmain(int argc, _TCHAR* argv[])
{
//u_long a = 0x12345678;
//u_long b = htonl(a);     //将主机的unsigned long 转为网络字节顺序(32位)
//u_long b = ntohl(a);     //将网络字节顺序(32位)转为主机字节


u_short a = 0x1234;
//u_short b = ntohs(a);//32位
u_short b = htons(a);
printf("%u\n",a);
printf("%x\n",a);
printf("%u\n",b);
printf("%x\n",b);


system("pause");
return 0;
}

 

 

 

通过转换,本来的字节顺序是1234,转换成网络顺序后成了3412.

作用相反的函数即把网络字节顺序转换成主机序列位ntohl()函数。

记忆这类函数,主要看前面的n和后面的hl。n代表网络,h代表主机host,l代表long的长度,

还有相对应的s带碧昂16位的short

 

同类的函数:ntohs(), htons() 就是转换成short类型的。

posted @ 2020-05-07 14:50  StudyToAll  阅读(694)  评论(0编辑  收藏  举报