再转一篇关于字节序的文章

大端和小端字节序 -- 大小端
    大端和小端字节序的问题在网络中以及在不同的操作系统的兼容性中是一个比较大的问题。它关系到不同操作系统和网络传输是否能够保证数据的语义正确性。
    对于一个字节而言,大端和小端没有任何的区别,但是对于多个字节而言,就存在着显著的区别。这个区别我们可以很容易想到,如果提供了一个地址,比如0x37041200,需要读取这个地址的一个字,也就是4个字节的一个数据。那么是读取从0x37041200开始到0x37041300这样的一个数,还是读取从0x37041200开始到0x37041100存储的4个字节的数。为此就出现了不同公司的两种实现--一个就是大端,一个就是小端。


你也可以用下面的程序测验你的机器是大端字节序还是小端字节序:
----------------------------------------------------------
#include <stdio.h>
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 <stdio.h>

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值