大端与小端
简介
数据存储在系统为它分配的内存空间中,从低地址空间开始,往高地址空间进行存储。
大端模式(big-endian):
数据的高字节部分保存在内存的低地址空间中,而数据的低字节部分保存在内存的高地址空间中。
小端模式(litter-endian):
数据的低字节部分保存在内存的低地址空间中,而数据的高字节部分保存在内存的高地址空间中
图示
数据:int data = 0x12345678;
存储的内存空间的起始地址:0x1000
假设转换时数据类型存储到 unsigned char buf[4];
大端模式(big-endian):
内存空间 | buf | 数据 |
---|---|---|
0x1003 | buf[3] | 0x78 |
0x1002 | buf[2] | 0x56 |
0x1001 | buf[1] | 0x34 |
0x1000 | buf[0] | 0x12 |
小端模式(litter-endian):
内存空间 | buf | 数据 |
---|---|---|
0x1003 | buf[3] | 0x12 |
0x1002 | buf[2] | 0x34 |
0x1001 | buf[1] | 0x56 |
0x1000 | buf[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;
}