- 一、字节序转换函数
- 二、使用步骤
- 总结
一、字节序转换函数
转换端口
uint16_t htons(uint16_t hostshort); //主机字节序->网络字节序
uint16_t ntohs(uint16_t netshort); //网络字节序->主机字节序
二、使用步骤转IP
uint32_t htons(uint32_t hostlong);//主机字节序->网络字节序
uint32_t ntohs(uint32_t netlong);//网络字节序->主机字节序
#include#include int main() { //htons 转换端口 unsigned short a=0x0102; printf("%xn",a); unsigned short b=htons(a); printf("%xn",b); printf("--------------------------------n"); //htonl 转换IP char buf[4]={192,168,1,100}; int num=*(int *)buf; int res=htonl(num); unsigned char* p=(char*)&res; printf("%d %d %d %dn",*p,*(p+1),*(p+2),*(p+3)); printf("--------------------------------n"); //ntohs unsigned char buf1[4]={1,1,168,192}; int num1=*(int*)buf1; int res1=ntohl(num1); unsigned char* p1=(unsigned char*)&res1; printf("%d %d %d %dn",*p1,*(p1+1),*(p1+2),*(p1+3)); printf("--------------------------------n"); //ntohl unsigned int c=0x12345678; printf("%xn",c); unsigned int d=htonl(c); printf("%xn",d); return 0; }
总结
本节主要介绍了字节序转换函数,以便在实际开发中使用。



