Little Endian, Big Endian, 网络字节序

字节序是指多字节数据在计算机内存中存储或者网络传输时各字节的存储顺序。

Little Endian还是Big Endian与操作系统和芯片类型都有关系。
Motorola的PowerPC系列CPU和Intel的x86系列CPU;
PowerPC系列采用big endian方式存储数据,而x86系列则采用little endian方式存储数据。

(1)Little endian: 将低字节存储在起始地址
0x12345678 on a little-endian system
Memory offset    0    1    2    3
Memory content    0x78    0x56    0x34    0x12

(2)Big endian: 将高字节存储在起始地址
0x12345678 on a big-endian system
Memory offset    0    1    2    3
Memory content    0x12    0x34    0x56    0x78

(3)Big endian vs. little endian
#include <stdio.h>
int main ()
{
    int i = 0x12345678;

    if (*(char *)&i == 0x12)
        printf ("Big endian\n");
    else if (*(char *)&i == 0x78)
        printf ("Little endian\n");

    return 0;
}


(4)网络字节序是TCP/IP中规定好的一种数据表示格式,它与具体的CPU类型、操作系统等无关,
从而可以保证数据在不同主机(不同程序)之间传输时能够被正确解释。
在IPV4,IPV6,TCP,UDP数据包中广泛采用Big endian数据格式化数据,所以Big endian又被称为网络字节序。

/* 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;
}


参考:
http://www.ibm.com/developerworks/library/l-port64/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值