How to assign value to a struct with bit-fields?

前端 未结 4 554
耶瑟儿~
耶瑟儿~ 2020-12-30 09:05

I have a struct with bit-fields (totally 32 bit width) and I have a 32-bit variable. When I try to assign the variable value to my struct, I got an error:

4条回答
  •  误落风尘
    2020-12-30 09:39

    Use a union.

    union foo {
        struct {
            uint8_t a : 4;
            uint8_t b : 4;
            uint8_t c : 4;
            uint8_t d : 4;
            uint16_t e;
        };
        uint32_t allfields;
    };
    
    int main(void) {
        union foo a;
    
        a.allfields = 0;
        a.b = 3;
    
        return 0;
    }
    

提交回复
热议问题