《UNIX Network Programming Volume1: The Socket Networking API, Third Edition》
W.Richard Stevens / Bill Fenner / Andrew M.Rudoff
考虑内存中存储一个16位整数,它由2个字节组成,因此存储这两个字节有两种方法:
- 小端字节序——将低序字节存储在起始地址;
- 大端字节序——将高序字节存储在起始地址。
MSB(most significant bit,最高有效位):是这个16位值最左边一位;
LSB(least significant bit,最低有效位):是这个16位值最右边一位。
- 主机字节序:某个给定系统所用的字节序。(遗憾的是,这两种字节序格式都有系统在使用。)
- 网络字节序:网际协议规定使用大端字节序来传送这些多字节整数。
(byteorder.c:在一个短整型变量中存放2字节的值0x0102,然后查看它的两个连续字节c[0]和c[1],以此确定主机字节序)
#include <stdio.h>
int main(int argc, char **argv) {
union {
short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
printf("Host byte order: ");
if (2 == sizeof(short)) {
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));
return 0;
}
结果(仅限测试主机):
Host byte order: little-endian