字节序总结
定义
- 大端存储(Big Endian):数据的高字节存储在低地址,低字节存储在高地址。
- 小端存储(Little Endian):数据的低字节存储在低地址,高字节存储在高地址。
二进制示例
- 十六进制数
0x12345678
的二进制表示:- 大端存储:内存中顺序为
12 34 56 78
- 地址 0x00:
00010010
- 地址 0x01:
00110100
- 地址 0x02:
01010110
- 地址 0x03:
01111000
- 地址 0x00:
- 小端存储:内存中顺序为
78 56 34 12
- 地址 0x00:
01111000
- 地址 0x01:
01010110
- 地址 0x02:
00110100
- 地址 0x03:
00010010
- 地址 0x00:
- 大端存储:内存中顺序为
如何判断(C 实现)
#include <stdio.h>
int main() {
union {
unsigned int i;
unsigned char c[4];
} test;
test.i = 0x01020304;
if (test.c[0] == 0x04 && test.c[1] == 0x03 && test.c[2] == 0x02 && test.c[3] == 0x01) {
printf("Little Endian\n");
} else if (test.c[0] == 0x01 && test.c[1] == 0x02 && test.c[2] == 0x03 && test.c[3] == 0x04) {
printf("Big Endian\n");
} else {
printf("Unknown Endian\n");
}
return 0;
}
- 使用联合体(union)来检查数据在内存中的字节顺序,从而判断系统的字节序。
字节序转换
-
从大端转换到小端:
uint32_t big_endian_value = 0x12345678; uint32_t little_endian_value = htonl(big_endian_value); // htonl函数将主机字节序转换为网络字节序(大端)
-
从小端转换到大端:
uint32_t little_endian_value = 0x78563412; uint32_t big_endian_value = ntohl(little_endian_value); // ntohl函数将网络字节序(大端)转换为主机字节序
-
htonl
和ntohl
函数用于在网络字节序(大端)和主机字节序之间进行转换。