原文:https://blog.hwg1998.com/blog/95
C++中有一个很神奇的类型——union共同体、或者说联合体。它提供了一个很便捷的功能,方便我们能对一块内存上的数据安装不同的格式去使用。
- 定义
union one4all
{
char c[4];
unsigned short s[2];
unsigned int in;
};
安装这种定义方式,这个联合体在内存中占据4个byte,32bit
- 安照不同的方式去读取
one4all te;
te.in = 0x12345678;
cout << te.s[0]<<" "<< te.s[1]<<endl;
输出结果如下:
22136 4660
这是在小端机器上的运行结果,如果是在大端机器上,那么具体的结果我还没有测试过。哈哈哈
-
应用
利用union这个特性,我们可以很方便的测试我们的机器是大端还是小端,具体的大端小端的理解,去这里看一下就明白了
上代码,如果是小端机器,上文定义的te在内存中的存储应该是像下面这样,如果把这个联合体看作一个short数组的话,对应关系如下:
0x78 0x56 0x34 0x12
short[0] short[1]
低 —> 高 //内存地址
那么short[0]对应的数值就是0x5678如果是大端模式
0x12 0x34 0x56 0x78 short[0] short[1] 低 --> 高 //内存地址
此时short[0]对应的值就应该是0x1234啦 , 如果short数组的下标是随着内存地址的递增而递增的话。
验证代码
```cpp
#include <iostream>
#include <bitset>
using namespace std;
union one4all
{
char c[4];
unsigned short s[2];
unsigned int in;
};
int main(){
one4all te;
te.in = 0x12345678;
bitset<32> bitsetv((te.in));
cout << bitsetv <<endl;
for(int i=0;i<4;i++)
cout << bitset<8>(te.c[i]) << " ";
cout <<endl;
cout << te.s[0]<<" "<< te.s[1]<<endl;
cout << "int:"<<te.in<<endl;
cout << sizeof(bool) << " " <<sizeof(char) << " "<<sizeof(short) << " "<< sizeof(int) << " " << sizeof(te)<<endl;
if(te.s[0] == 0x5678)
cout << endl << "this machine is little-endian"<< endl;
else if(te.s[1] == 0x5678)
cout << endl << "this machine is big-endian"<< endl;
else
cout << "can not judge"<< endl;
return 0;
}
```
输出结果
```cpp
00010010001101000101011001111000
01111000 01010110 00110100 00010010
22136 4660
int:305419896
1 1 2 4 4
this machine is little-endian
```
本文介绍了C++中的联合体(Union)特性,通过实例展示了如何定义和使用Union,以及如何利用Union来判断机器是大端还是小端。在小端机器上,Union内的short数组存储为0x5678, 而在大端机器上,这个值则为0x1234。"
129685293,8056929,使用Python爬取ClinicalTrials网站数据,"['Python', '网络爬虫']
1369

被折叠的 条评论
为什么被折叠?



