大端小端:
所谓的大端模式,是指数据的低位保存在内存的高地址中,而数据的高位,保存在内存的低地址中;
所谓的小端模式,是指数据的低位保存在内存的低地址中,而数据的高位保存在内存的高地址中。
32bit宽的数0x12345678在Little-endian模式CPU内存中的存放方式(假设从地址0x4000开始存放)为:
内存地址 | 0x4000 | 0x4001 | 0x4002 | 0x4003 |
存放内容 | 0x78 | 0x56 | 0x34 | 0x12 |
而在Big-endian模式CPU内存中的存放方式则为:
内存地址 | 0x4000 | 0x4001 | 0x4002 | 0x4003 |
存放内容 | 0x12 | 0x34 | 0x56 | 0x78 |
共同体:
union 联合名
{
成员表
};
成员表公用一段内存, 对于联合的不同成员赋值, 将会对其它成员重写, 原来成员的值就不存在了
应用:
1、判断大端还是小端
#include <iostream>
using namespace std;
union T
{
char c[4];
int i;
};
void main()
{
T t;
t.i=1;
if(t.c[0]==1)
cout<<"小端"<<endl;
else
cout<<"大端"<<endl;
system("pause");
}
2、int、float、double类型在内存中的表示
在按字节方式进行数据通信时,需要发送int、float、double等数据类型。这里就需要把int、float、double这些类型用字节方式表示。
#include <iostream>
using namespace std;
union FourBytes
{
char c[4];
int i;
float f;
};
void main()
{
FourBytes fb1,fb2;
float f_data=987.654;
fb1.f=f_data;
//相当于通信中的发送、接收
for(int i=0;i<4;i++)
{
fb2.c[i]=fb1.c[i];
}
//显示接收到的数据
cout<<fb2.f<<endl;
system("pause");
}
只写了int和float的,double也一样,只要char c[8]就行了
2、笔试题目
#include
union
{
int i;
char x[2];
}a;
void main()
{
a.x[0] = 10;
a.x[1] = 1;
printf("%d",a.i);
}
答案:266 (低位低地址,高位高地址,内存占用情况是 Ox010A)
b)
main()
{
union{ /*定义一个联合*/
int i;
struct{ /*在联合中定义一个结构*/
char first;
char second;
}half;
}number;
number.i=0x4241; /*联合成员赋值*/
printf("%c%c\n", number.half.first, mumber.half.second);
number.half.first='a'; /*联合中结构成员赋值*/
number.half.second='b';
printf("%x\n", number.i);
getch();
}
答案:AB (0x41 对应'A',是低位;Ox42 对应'B',是高位)
6261 (number.i 和 number.half 共用一块地址空间), 注意是十六进制的输出,十进制的话是25185