【发布时间】:2017-03-11 08:46:24
【问题描述】:
我想在下面的结构中打印位域的位表示。但是,当我打印内容时,我只是一遍又一遍地看到第一个位字段的值。我究竟做错了什么?
#include <stdio.h>
#include <limits.h>
typedef struct Bits {
union BitUnion {
unsigned int op1 : 8;
unsigned int op2 : 8;
unsigned int op3 : 8;
unsigned int op4 : 8;
int num;
} BitUnion;
} Bits;
void printBitNum(Bits b);
int main() {
Bits test;
test.BitUnion.op1 = 2;
test.BitUnion.op2 = 5;
test.BitUnion.op3 = 'd';
test.BitUnion.op4 = 10;
printBitNum(test);
return 0;
}
void printBitNum(Bits b) {
int i;
for (i = (CHAR_BIT * sizeof(int)) - 1; i >= 0; i--) {
if (b.BitUnion.num & (1 << i)) {
printf("1");
} else {
printf("0");
}
}
printf("\n");
}
【问题讨论】:
标签: c bits bit-fields