主机字节序和网络字节序
小端模式:低序字节储存在起始地址的排序方式称为小端模式,
大端模式:高序字节储存在起始地址的排序方式称为大端模式。
主机字节序:大端和小端模式都有使用的系统,当前系统使用的字节序称为主机字节序
网络协议栈必须对网络上的字节序达成一致,保证数据的正常传输,因此网络上采用大端字节序来传递多字节整数。主机字节序和网络字节序之间的转换API如下所示:
#include <netinet/in.h>
uint16_t htons(uint16_t h);//host short --> net short
uint32_t htonl(uint32_t h);//host long --> net long
uint16_t ntohs(uint16_t n);//net short --> host short
uint32_t ntohl(uint32_t n);//net long --> host long
一个简单的判断主机字节序的代码:
#include <stdio.h>
int
main(int argc, char **argv)
{
union {
short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
if (sizeof(short) == 2) {
if (un.c[0] == 1 && un.c[1] == 2)
printf("this is big-end system\n");
if (un.c[0] == 2 && un.c[1] == 1)
printf("this is small-end system\n");
else
printf("unknow byteorder system\n");
}
return 0;
}