大端模式与小端模式

大端与小端



简介

  数据存储在系统为它分配的内存空间中,从低地址空间开始,往高地址空间进行存储。

大端模式(big-endian):

数据的高字节部分保存在内存的低地址空间中,而数据的低字节部分保存在内存的高地址空间中。

小端模式(litter-endian):

数据的低字节部分保存在内存的低地址空间中,而数据的高字节部分保存在内存的高地址空间中


图示

数据:int data = 0x12345678;
存储的内存空间的起始地址:0x1000
假设转换时数据类型存储到 unsigned char buf[4];

大端模式(big-endian):

内存空间buf数据
0x1003buf[3]0x78
0x1002buf[2]0x56
0x1001buf[1]0x34
0x1000buf[0]0x12

  
小端模式(litter-endian):

内存空间buf数据
0x1003buf[3]0x12
0x1002buf[2]0x34
0x1001buf[1]0x56
0x1000buf[0]0x78

参考理解

  单词endian可以理解为:字节存储次序,换句话,可以理解为数据的各个字节在内存空间存储的顺序。同时,数据在内存中是从低地址空间开始存储的。

  对于大端模式(big-endian)可以理解为数据高字节部分在内存空间的存储顺序,即高字节部分先存在低地址空间中。

  对于小端模式(litter-endian)可以理解为数据低字节部分在内存空间的存储顺序,即低字节先存在低地址空间中。


测试代码

#include <iostream>

using namespace std;

void testEndian()
{
    int data = 0x12345678;
    unsigned char* pData = reinterpret_cast<unsigned char *>(&data);

    cout << "the data : " << hex << data << endl;

    cout << "the first address for storing data into memory : " << &data << endl;

    cout << "the data in the first address : " << hex << static_cast<unsigned short>(pData[0]) << endl;

    cout << "the last address for storing data into memory : " << &data + 3 << endl;

    cout << "the data in the last address : " << hex << static_cast<unsigned short>(pData[3]) << endl;

    if(pData[0] == 0x12 && pData[3] == 0x78)
        cout << "this is a big-endian." << endl;
    else
        cout << "this is a litter-endian." << endl;
}

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值