Endianness
计算机科学中描述多字节数据在内存中存储顺序的核心概念
高位字节 → 低地址
低位字节 → 高地址
符合人类阅读习惯
低位字节 → 低地址
高位字节 → 高地址
符合计算机处理习惯
Different System Implementations
Big-Endian Systems
Little-Endian Systems
Bi-Endian Systems
Endianness Detection Methods
指针类型转换检测
bool is_little_endian() {
unsigned int x = 1;
return *((unsigned char *)&x) == 1;
}
通过检查整数1的最低字节来判断字节序
联合体检测方法
union {
unsigned int i;
unsigned char c[4];
} u;
u.i = 0x12345678;
if (u.c[0] == 0x78) {
printf("系统是小端序\n");
} else {
printf("系统是大端序\n");
}
使用联合体直观地观察字节存储顺序
Practical Applications
Network Communication
统一使用大端序作为标准
// 转换函数
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
File Formats
Cross-platform Development
Historical Origin
"大端"和"小端"术语源自乔纳森·斯威夫特的小说《格列佛游记》。小人国的人们为了吃鸡蛋应该从大头(Big-End)还是小头(Little-End)敲开而争论不休,甚至为此发动了战争。
1980年,丹尼·科恩在论文《论大端和小端》中借用了这个典故来描述字节序。
Summary & Key Points
符合人类阅读习惯
高位字节在前
符合计算机处理习惯
低位字节在前
统一采用大端序
确保数据一致性
网络编程、文件格式
跨平台开发
多字节数据的存储顺序决定了系统的字节序特性
不同系统间通信需要进行适当的字节序转换
了解字节序对于底层开发和系统集成至关重要