推荐阅读深入浅出大小端模式、如何测试电脑大小端、测试机器大小端的方法
一、渊源:自Jonathan Swift的《格列夫游记》中出现大小端后,现特指数据存储顺序的分歧。
二、来由:每个地址单元都对应1Byte。存在将多字节数据如何存放的问题。
三、Little-endian:数据的高字节保存在内存高地址中,数据的低字节保存在内存的低地址中,该模式将地址高低和权值有效结合。Big-endian:与Little-endian相反;地址由小向大增加,数据按高位向低位存放。
四、在网络上传输数据,因收发端硬件平台不同,存储顺序可能不同。TCP/IP协议规定在网络上必须采用大端模式,在数据发送之前将转换成大端模式。
五、测试方法,两种非常经典的办法:
#include<stdio.h>
bool IsLittleEndian()
{
int test = 1;
if (*((char *)&test))
return true;
else
return false;
}
int main()
{
if (IsLittleEndian())
printf("Little Endian!\n");
else
printf("Big Endian!\n");
}
#include<stdio.h>
#include<string.h>
typedef union Test //大小占4个字节
{
int i;
char c;
}Test;
bool IsLittleEndian() //利用联合体特性
{
Test test;
memset(&test, 0, sizeof(Test));
test.i = 1;
if (test.c == 1)
return true;
else
return false;
}
int main()
{
if (IsLittleEndian())
printf("Little Endian!\n");
else
printf("Big Endian!\n");
}