字节序转换函数

593 词

主机字节序

主机字节序就是主机存储数据的顺序,有大端序小端序两种

  • 大端序:高位字节存储在低地址上,低位字节存储在高地址上
  • 小端序:低位字节存储在低地址上,高位字节存储在高地址上

网络字节序

网络字节序就是网络传输数据的顺序,规定为大端序

主机字节序转网络字节序

htonl

Host to Network Long
将主机字节序转换成网络字节序

1
2
3
4
#include <arpa/inet.h>

unsigned long int htonl(
unsigned long int hostlong);

htons

Host to Network Short
将主机字节序转换成网络字节序

1
2
3
4
#include <arpa/inet.h>

unsigned short int htons(
unsigned short int hostshort);

网络字节序转主机字节序

ntohl

Network to Hos Long
将网络字节序转换成主机字节序

1
2
3
4
#include <arpa/inet.h>

unsigned long int ntohl(
unsigned long int netlong);

ntohs

Network to Host Short
将网络字节序转换成主机字节序

1
2
3
4
#include <arpa/inet.h>

unsigned short int ntohs(
unsigned short int netshort);