endian
就是字节顺序的意思
big-endian
现在在纸上书写阿拉伯数字198,我们肯定是先写最高位1,直到写到最低位8,如果让计算机采用这个顺序存放数据到内存中,也就是现在起始地址放最高位1,然后写上9,最好是8.这样的顺序就是big endian.
little-endian
与其顺序相反的是,低位地址存放低位数字,高位地址存放高位数字。这种最合乎计算机内存地址的写法就是little endian.
如果没有明白我说的,看下面的表。
Endian | First byte (lowest address) | Middle bytes | Last byte (highest address) | Notes |
---|---|---|---|---|
big | mostsignificant | ... | leastsignificant | Similar to a number written on paper (inArabic numeralsas used in most Western scripts) |
little | leastsignificant | ... | mostsignificant | Arithmetic calculation order (seecarry propagation) |
下面的函数帮助判断是big-endian还是little-endian. 很简单,取最低位字节的整数,比较是不是最低位数字ff,是就是little-endian.
bool little_endian(){
int x = 0x00ff;
char* p = (char*)&x;
return (int)p[0]==-1;
}
字节顺序是由CPU体系结构或者其他硬件决定的。下面的描述同样来自于wikipedia
Well-known processors that use the big-endian format includeMotorola 6800and68k, XilinxMicroblaze,IBM POWER, andSystem/360and its successors such asSystem/370,ESA/390, andz/Architecture. ThePDP-10also used big-endian addressing for byte-oriented instructions.SPARChistorically used big-endian until version 9, which is bi-endian, similarly theARM architecturewas little-endian before version 3 when it became bi-endian, and thePowerPCandPower Architecturedescendants of IBM POWER are also bi-endian (see below).
Serial protocols may also be regarded as either little or big-endian at the bit- and/or byte-levels (which may differ). Many serial interfaces, such as the ubiquitousUSB, are little-endian at the bit-level. Physical standards likeRS-232,RS-422andRS-485are also typically used withUARTsthat send the least significant bit first, such as in industrial instrumentation applications, lighting protocols (DMX512), and so on. The same could be said for digitalcurrent loopsignaling systems such asMIDI. There are also several serial formats where the most significant bit is normally sent first, such asI²Cand the relatedSMBus. However, the bit order may often be reversed (or is "transparent") in the interface between theUARTorcommunication controllerand the hostCPUorDMAcontroller (and/or system memory), especially in more complex systems and personal computers. These interfaces may be of any type and are often configurable.