所谓大小端模式,就是一个关于数据字节在存储顺序的问题。在某些编程环境中,了解大小端是非常重要的,比如汇编和网络编程中,对存取和发送、接收数据的字节序都有严格的要求。当然,在高层次,你很少会需要考虑到这些。为什么会有大小端模式之分呢?这是因为在计算机系统中,我们是以字节为单位的,每个地址单元都对应着一个字节。在许多计算机语言中,许多数据类型都是多字节的,这就产生了多字节数据在内存中存放数据的问题。在大端模式(Big-endian)中,数据的低位(就是权值较小的后面那几位)保存在内存的高地址中,而数据的高位,保存在内存的低地址中;在小端模式(Little-endian)中,数据低位就存放在内存的低位。了解了什么是大小端,看下面的程序,输出结果是什么?
1 2 3 4 5 6 7 8 9 10 | #include <stdio.h> int main() { int a[] = {1, 2, 3, 4, 5}; int *ptr1 = (int*) (&a + 1) - 1; int *ptr2 = (int*) ((int)a + 1); printf("%x, %x\n", *ptr1, *ptr2); return 0; } |
在我的机器上的输出时5, 2000000,可以看出是处理器是小端模式的。为什么呢?
首先*ptr1 == 5是没有疑问的。
再看看,*ptr2:
| 内存编号 | 0 | 1 | 2 | 3 | 4 | …… |
| 数据内容(16进制) | 0×01 | 0×00 | 0×00 | 0×00 | 0×02 | …… |
指针ptr2指向1号单元,因此*ptr2就是0×02000000。在大端模式的机器中内存布局应该是这样滴:
| 内存编号 | 0 | 1 | 2 | 3 | 4 | …… |
| 数据内容(16进制) | 0×00 | 0×00 | 0×00 | 0×01 | 0×00 | …… |
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
太巧了,我也刚写了差不多的文章。
程序是一样的,QQ群里的同学说是C++ Primer Plus的习题。
去年去笔试中兴,考到一个大端小端的问题,人家说“…是intel处理器…”。
IA-32架构的似乎都是Little-endian。我见过的Big-endian都是单片机。
我在CSDN上看到的。
是的,intel的是小端。下面一段话来自 CSAPP 27页:
“The former convention—where the least significant byte comes first—is referred to as little endian. This convention is followed by most machines from the former Digital Equipment Corporation (now part of Compaq Corporation), as well as by Intel. The latter convention—where the most significant byte comes first—is referred to as big endian. This convention is followed by most machines from IBM, Motorola, and Sun Microsystems. Note that we said “most.” The conventions do not split precisely along corporate boundaries. For example, personal computers manufactured by IBM use Intel-compatible processors and hence are little endian. Many microprocessor chips, including Alpha and the PowerPC by Motorola can be run in either mode, with the byte ordering convention determined when the chip is powered up.”
DEC和Intel大多是小端;IBM,Moto,Sun大多是大端,但IBM PC是小端;Alpha,PowerPC可运行在两种模式,这在加电时确实。