【问题标题】:How to print multiple bit-fields of length 8 in a struct in C如何在C中的结构中打印长度为8的多个位域
【发布时间】: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


    【解决方案1】:

    union 表示所有成员共享同一个地址。所以op1、op2、op3 和op4 都命名了相同的内存位置。

    因此,您的代码将该位置设置为 10,然后尝试打印出大部分未初始化的变量。

    我猜你的意思是有两个成员的联合:int 和一个包含四个位域的结构。

    【讨论】:

    • 你完全正确!将数据结构更改为联合托管 struct 和 int 后,一切正常。
    猜你喜欢
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多