30 lines
675 B
C
30 lines
675 B
C
|
// 共用体和结构体结合使用
|
||
|
// 可以解决不同类型的数据在内存中的存储问题
|
||
|
#include <stdio.h>
|
||
|
|
||
|
struct REG
|
||
|
{
|
||
|
unsigned char a : 1; // 低位
|
||
|
unsigned char b : 1;
|
||
|
unsigned char c : 1;
|
||
|
unsigned char d : 1;
|
||
|
unsigned char e : 1;
|
||
|
unsigned char f : 1;
|
||
|
unsigned char g : 1;
|
||
|
unsigned char h : 1; // 高位
|
||
|
};
|
||
|
|
||
|
union REG_UNI
|
||
|
{
|
||
|
struct REG reg;
|
||
|
unsigned char ch;
|
||
|
};
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
union REG_UNI reg1 = {{1, 0, 0, 0, 1, 0, 0, 0}};
|
||
|
// reg1.ch 可以把每一位的值都取出来,但是不能修改,读取顺序是从低位到高位,倒序读取 0b00001001
|
||
|
printf("%#x\n", reg1.ch); // 0x11
|
||
|
|
||
|
return 0;
|
||
|
}
|