computer:c:tips:byte_order
这是本文档旧的修订版!
字节序(Byte order)
对于字节编址(byte-addressable)的计算机,通常存在两种字节序:
- 高端字节序(big-endian, left-to-right)
- 小端字节序(little-endian, right-to-left)
比如一个32位(4字节)的整数0x01020304,下面是两种字节序的存储图示(A代表地址):
高端字节序 | ||||
---|---|---|---|---|
01 | 02 | 03 | 04 | … |
A | A+1 | A+2 | A+3 | A+4 |
小端字节序 | ||||
---|---|---|---|---|
04 | 03 | 02 | 01 | … |
A | A+1 | A+2 | A+3 | A+4 |
对于高端字节序,起始地址单元存放的是整数的最左(leftmost)或最高位字节(high-order byte)。而小端字节序则相反,起始地址单元存放的是整数的最右(rightmost)或最低位字节(low-order byte)。
下面是一个测试本机字节序的程序(这里union的用法是不可移植的):
#include <stdio.h> #include <stdlib.h> union { int i; char c[sizeof(int)]; } u; int main(void) { u.i = 1; if (u.c[0] == 1) printf("little-endian\n"); else if (u.c[sizeof(int) - 1] == 1) printf("big-endian\n"); else printf("unknown\n"); exit(0); }
computer/c/tips/byte_order.1409915892.txt.gz · 最后更改: 2014/11/01 02:02 (外部编辑)