小端:低地址低位,高地址高位!
判断系统是大端还是小端
#include <iostream>
using namespace std;
union Test{
short value;
char bytes[2];
};
int main()
{
Test test_value;
test_value.value = 0x1234;
if (test_value.bytes[0] == 0x12 && test_value.bytes[1] == 0x34)
cout << "big ending" << endl;
else if (test_value.bytes[0] == 0x34 && test_value.bytes[1] == 0x12)
cout << "little ending" << endl;
else
cout << "use test_value error" << endl;
return 0;
}
struct与union
- struct和union都是由多个不同的数据类型成员组成,但在任何同一时刻,union中只存放了一个被选中的成员(所有成员共用一块地址空间),而struct的所有成员都存在(不同成员的存放地址不同)。
- 对于union的不同成员赋值,将会对其它成员重写,原来成员的值就不存在了,而对于struct的不同成员赋值是互不影响的。
#include <iostream>
using namespace std;
union{
int i;
char x[2];
}a;
int main()
{
a.x[0] = 10;
a.x[1] = 1;
cout << a.i << endl; //266
}
在上述程序中,int占4个字节,x占2个字节,内存对齐(参考之前关于内存对齐的总结),总的大小为4个字节。
解释一下上图中的内存结果:从低地址开始存数据,因为是小端,所以先存低位数据,也就是存x[0]的数据10(即0A),再存1(即01),故内存占用情况是0x 00 00 01 0A,所以 i 也为0x 00 00 01 0A,换算结果为:1×16^2+10×16^0 = 266。
当然,如果是struct就输出默认值0了,因为x的赋值跟i没有任何关系。