I want to print the bit representation of bit-fields in the struct below. However when I print the contents I just keep seeing the value of the first bit-field over and over again. What am I doing wrong?
#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");
}
union
means that all members share the same address. So op1
, op2
, op3
and op4
all name the same memory location.
So your code sets that location to 10
and then attempts to print out mostly uninitialized variables.
I guess you meant to have the union with two members: the int
, and a struct containing the four bitfields.