字节顺序
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 | most significant | ... | least significant | Similar to a number written on paper (in Arabic numerals as used in most Western scripts) |
little | least significant | ... | most significant | Arithmetic calculation order (see carry propagation) |
下面的函数帮助判断是big-endian还是little-endian. 很简单,取最低位字节的整数,比较是不是最低位数字ff,是就是little-endian.
bool IsLittleEndian(){ short int x = 0x00ff; char* p = (char*)&x; return (short int)p[0] == -1; }
另外根据chumine的提醒,下面这个来自Linux内核的实现效率更高:
static union { char c[4]; unsigned char l; } endian_test = {{"l","?","?","b"}}; #define IsLittleEndian2() (endian_test.l == "l")
字节顺序是由CPU体系结构或者其他硬件决定的。下面的描述同样来自于wikipedia
Well-known processors that use the big-endian format include Motorola 6800 and 68k, Xilinx Microblaze, IBM POWER, and System/360 and its successors such as System/370, ESA/390, and z/Architecture. The PDP-10 also used big-endian addressing for byte-oriented instructions.SPARC historically used big-endian until version 9, which is bi-endian, similarly the ARM architecture was little-endian before version 3 when it became bi-endian, and the PowerPC and Power Architecture descendants 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 ubiquitous USB, are little-endian at the bit-level. Physical standards like RS-232, RS-422 and RS-485 are also typically used with UARTsthat send the least significant bit first, such as in industrial instrumentation applications, lighting protocols (DMX512), and so on. The same could be said for digital current loop signaling systems such as MIDI. There are also several serial formats where the most significant bit is normally sent first, such as I²C and the related SMBus. However, the bit order may often be reversed (or is "transparent") in the interface between the UART or communication controller and the host CPU or DMA controller (and/or system memory), especially in more complex systems and personal computers. These interfaces may be of any type and are often configurable.
- 上一篇:没有了
- 下一篇: Nginx 反向代理设置