1.小端和大端(一)
小端:在最小内存地址,先存储最低有效字节。
大端:在最小内存地址,先存储最高有效字节。
实例:
一个4字节整数:s = 0x03020100;
备注:参考《Linux/UNIX系统编程手册》。
2.小端和大端(二)
小端(little-endian)字节序:低序字节存储在起始地址;
大端(big-endian)字节序:高序字节存储在起始地址。
《UNIX网络编程卷1》中有句话,非常精辟。
术语“小端”和“大端”表示多个字节值的哪一端(小端——低序字节或大端——高序字节)存储在该值的起始地址。
《UNIX网络编程卷1》中有一个实例代码,结合它,我们可以更好理解小端和大端。
#include "unp.h"
int main(int argc, char **argv)
{
union {
short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
printf("%s: ", CPU_VENDOR_OS);
if (sizeof(short) == 2) {
if (un.c[0] == 1 && un.c[1] == 2)
printf("big-endian\n");
else if (un.c[0] == 2 && un.c[1] == 1)
printf("little-endian\n");
else
printf("unknown\n");
} else
printf("sizeof(short) = %d\n", sizeof(short));
exit(0);
}
3.主机字节序和网络字节序之间的转换函数
网际协议使用大端字节序来传送这些多字节整数。套接字地址结构中的某些字段必须按照网络字节序进行维护。因此我们要关注如何在主机字节序和网络字节序之间相互转换。我们使用到4个函数:
#include <netinet/in.h>
uint16_t htons(uint16_t host16bitvalue);
uint32_t htonl(uint32_t host32bitvalue);
Both return: value in network byte order
uint16_t ntohs(uint16_t net16bitvalue);
uint32_t ntohl(uint32_t net32bitvalue);
Both return: value in host byte order
上述函数名中:
h--host
n--network
s--short
l--long
当使用这些函数时,我们并不关心主机字节序和网络字节序的实际值(究竟是大端还是小端)。我们所要做的只是调用适当的函数在主机和网络字节序之间转换某个给定值。