大端序指多字节数据在内存进行存储时,高字节的数据存储在低位地址。小端序则是高字节数据存储在高位字节。
以下面的代码为例:
#include <stdio.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
uint32_t data = 0x12345678;
//获取data的起点字节地址
uint8_t* byte_ptr = (uint8_t*)&data;
cout<<"data数据:0x"<<hex<<data<<endl;
cout<<"data0数据"<<hex<<static_cast<int>(byte_ptr[0])<<endl; //cout会将uint8_t视为字符输出,因此不能static_cast<uint8_t>
cout<<"data0地址"<<hex<<static_cast<void*>(&byte_ptr[0])<<endl;
cout<<"data1数据"<<hex<<static_cast<int>(byte_ptr[1])<<endl;
cout<<"data1地址"<<hex<<static_cast<void*>(&byte_ptr[1])<<endl;
cout<<"data2数据"<<hex<<static_cast<int>(byte_ptr[2])<<endl;
cout<<"data2地址"<<hex<<static_cast<void*>(&byte_ptr[2])<<endl;
cout<<"data3数据"<<hex<<static_cast<int>(byte_ptr[3])<<endl;
cout<<"data3地址"<<hex<<static_cast<void*>(&byte_ptr[3])<<endl;
uint16_t* byte_ptr16 = (uint16_t*)&data;
//cout<<"data数据:0x"<<hex<<data<<endl;
cout<<"data0数据"<<hex<<static_cast<int>(byte_ptr16[0])<<endl;
cout<<"data0地址"<<hex<<static_cast<void*>(&byte_ptr16[0])<<endl;
cout<<"data1数据"<<hex<<static_cast<int>(byte_ptr16[1])<<endl;
cout<<"data1地址"<<hex<<static_cast<void*>(&byte_ptr16[1])<<endl;
}
输出结果如下:
data数据:0x12345678
data0数据78
data0地址0x7ffe20dfb9c4
data1数据56
data1地址0x7ffe20dfb9c5
data2数据34
data2地址0x7ffe20dfb9c6
data3数据12
data3地址0x7ffe20dfb9c7
data0数据5678
data0地址0x7ffe20dfb9c4
data1数据1234
data1地址0x7ffe20dfb9c6
可以看出当前设备为小端序,表现为存储32位整型数据时,低字节数据(78)地址在低位。
要注意两个设备在和同一块内存进行交互时,要注意端序是否一致。比如大端序设备A向内存中写入数据0x12345678,小端序设备B从内存中读取该数据时(若不做处理)为0x78563412,还需要进行高低字节转换才可以读到正确的数据。