Big Endian和Little Endian那点儿事

big endian 和little endian都是字节序,指的是两种数据存储顺序。对于单字节数据类型,就不用考虑这个了。如果单机运行,不和别人程序交互,也不用考虑这个。 其他情况,比如网络通信,C++程序和Java程序通信,等等就一定要注意字节序了。也就主要考虑多字节数据类型。最常见的就是2字节short和4字节int了。 再说字节序前,先说两个概念,就是MSB和LSB。 MSB:Most significant bit, 二进制表示中的最高位。 LSB: Least significant bit, 二进制表示中的最低位。

big endian是指低地址存放最高有效字节(MSB),而little endian则是低地址存放最低有效字节(LSB)。恩这样也许更好记一些。LLL: **L**ittle Endian, the **L**east significant byte goes into the **L**owest-addressed slot”。

C/C++程序编译与平台紧密相关,他的数据存储顺序也一样。Intel的x86系列CPU采用的是little endian。motorola, IBM, Sun之类的CPU采用的是big endian。 Java语言诞生于Solaris ,而最初Solaris运行在Sun Sparc CPU上。 java为了支持跨平台,在操作系统上面加了一层JVM。 所以java程序在内存存储数据是采用big endian。底层的细节就交给JVM了。 java.nio.ByteOrder提供方法来判断所在的平台采用的是何种字节序。bo = ByteOrder.nativeOrder() ; 返回的值可能是ByteOrder.BIG_ENDIAN, 或者ByteOrder.LITTLE_ENDIAN。 试想,如果你用C/C++语言在Intel x86平台编写的程序跟别人的JAVA程序互通时会产生什么结果?可能你发给他0x1234,他看到的却是0x3412。 另外所有网络协议也都是采用big endian的方式来传输数据的。所以big endian方式也是网络字节序。当两台采用不同字节序的主机通信时,在发送数据之前都必须经过字节序的转换成为网络字节序后再进行传输。ANSI C中提供了下面四个转换字节序的宏。 ntoh:network->host hton:host->network ntohs和htons针对2字节的数 ntohl和htonl针对4字节的数

基本思想就是移位操作了。

/* C function to change endianness for byte swap in an unsigned 32-bit integer */uint32_t ChangeEndianness(uint32_t value){uint32_t result = 0;result |= (value & 0x000000FF) << 24;result |= (value & 0x0000FF00) << 8;result |= (value & 0x00FF0000) >> 8;result |= (value & 0xFF000000) >> 24; return result;}

Big Endian 比较符合思维习惯。判别一个数的正负很容易,只要取offset0处的一个字节就能确认。 Little Endian 长度为1,,2,4字节的数,排列方式都是一样的,数据类型转换非常方便。 比如32位内存地址开始连续四个字节存了4A 00 00 00。那么从这个地址读byte就是4A, 读short类型就是004A,读24位就是00004A,读int就是0000004A。所有值都是一样的。类型转换非常容易。都不用修改地址。在代码优化,汇编语言中little endian比较有用。

一些常见文件的字节序 来自:Dr. William T. Verts, April 19, 1996

Common file formats and their endian order are as follows: Adobe Photoshop – Big Endian BMP (Windows and OS/2 Bitmaps) – Little Endian DXF (AutoCad) – Variable GIF – Little Endian IMG (GEM Raster) – Big Endian JPEG – Big Endian FLI (Autodesk Animator) – Little Endian MacPaint – Big Endian PCX (PC Paintbrush) – Little Endian PostScript – Not Applicable (text!) POV (Persistence of Vision ray-tracer) – Not Applicable (text!) QTM (Quicktime Movies) – Little Endian (on a Mac!) (PeterLee注Big Endian in my opinion) Microsoft RIFF (.WAV & .AVI) – Both Microsoft RTF (Rich Text Format) – Little Endian SGI (Silicon Graphics) – Big Endian Sun Raster – Big Endian TGA (Targa) – Little Endian TIFF – Both, Endian identifier encoded into file WPG (WordPerfect Graphics Metafile) – Big Endian (on a PC!) XWD (X Window Dump) – Both, Endian identifier encoded into file

由于CPU存储数据操作的最小单位是一个字节,网络传输也是以字节为单位。其内部的比特序是什么样对我们的程序来说是不那么关心的。

旅行,其实是需要具有一些流浪精神的,

Big Endian和Little Endian那点儿事

相关文章:

你感兴趣的文章:

标签云: