qfedu-c-level/day13/d5.c

33 lines
628 B
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct
{
unsigned char a : 2;
unsigned char : 1; // 占位符
unsigned char b : 2;
unsigned char : 1; // 占位符
unsigned char c : 2;
} REG;
int main()
{
REG.a = 3;
REG.b = 1;
REG.c = 2;
printf("%ld B\n", sizeof(REG)); // 1 B
char reg = *((char *)&REG); // 原理: 位段的内存存储是从低位到高位的
printf("%#hhx\n", reg); // 0x11
// 打印二进制
printf("reg = 0b");
for (int i = 7; i >= 0; i--)
{
printf("%d", (reg >> i) & 1);
}
printf("\n");
return 0;
}