大端和小端字节序的问题在网络中以及在不同的操作系统的兼容性中是一个比较大的问题。它关系到不同操作系统和网络传输是否能够保证数据的语义正确性。
对于一个字节而言,大端和小端没有任何的区别,但是对于多个字节而言,就存在着显著的区别。这个区别我们可以很容易想到,如果提供了一个地址,比如0x37041200,需要读取这个地址的一个字,也就是4个字节的一个数据。那么是读取从0x37041200开始到0x37041300这样的一个数,还是读取从0x37041200开始到0x37041100存储的4个字节的数。为此就出现了不同公司的两种实现--一个就是大端,一个就是小端。
你也可以用下面的程序测验你的机器是大端字节序还是小端字节序:
----------------------------------------------------------
#include
int IsLittleEndian()
{
unsigned int usData = 0x12345678;
unsigned char *pucData = (unsigned char*)&usData;
if(*pucData == 0x78)
return 1;
else
return 0;
}
int main(void)
{
if(IsLittleEndian())
printf("is little endian!\n");
else
printf("is big endian!\n");
return 0;
}
a=0x12345678
----------------------------------------------------------
"Little Endian" means that the low-order byte of the number is stored in memory at the lowest address, and the high-order byte at the highest address. (The little end comes first.) For example, a 4 byte LongInt
Byte3 Byte2 Byte1 Byte0
will be arranged in memory as follows:
Base Address+0 Byte0 78h
Base Address+1 Byte1 56h
Base Address+2 Byte2 34h
Base Address+3 Byte3 12h
Intel processors (those used in PC's) use "Little Endian" byte order.
"Big Endian" means that the high-order byte of the number is stored in memory at the lowest address, and the low-order byte at the highest address. (The big end comes first.) Our LongInt, would then be stored as:
Base Address+0 Byte3 --12h
Base Address+1 Byte2 34h
Base Address+2 Byte1 56h
Base Address+3 Byte0 78h
Motorola processors (those used in Mac's) use "Big Endian" byte order
Intel的X86体系结构是Little Endian
----------------------------------------------------------
#include
int main()
{
int i = 0x11223344;
int j = 0;
char * a = (char *)&i;
printf("&a[0] = %p\n", &a[0]);
printf("&a[3] = %p\n", &a[3]);
for (j = 0; j < 4; j++)
printf("%x\n", a[j]);
}
--------------------------------
&a[0] = 0xbf82d048
&a[3] = 0xbf82d04b
44
33
22
11
|----------|
| 11 |
|----------| 0xbf82d04b
| 22 |
|----------| 0xbf82d04a
| 33 |
|----------| 0xbf82d049
| 44 |
|----------|<-- a 0xbf82d048
0x11223344
阅读(1480) | 评论(0) | 转发(0) |