简体   繁体   中英

How to print multiple bit-fields of length 8 in a struct in C

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM