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

前端 未结 4 542
耶瑟儿~
耶瑟儿~ 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:19

    You should never rely on how the compiler lays out your structure in memory. There are ways to do what you want with a single assignment, but I will neither recommend nor tell you.

    The best way to do the assignment would be the following:

    static inline void to_id(struct CPUid *id, uint32_t value)
    {
        id->Stepping         = value & 0xf;
        id->Model            = value >> 4 & 0xf;
        id->FamilyID         = value >> 8 & 0xf;
        id->Type             = value >> 12 & 0x3;
        id->Reserved1        = value >> 14 & 0x3;
        id->ExtendedModel    = value >> 16 & 0xf;
        id->ExtendedFamilyID = value >> 20 & 0xff;
        id->Reserved2        = value >> 28 & 0xf;
    }
    

    And the opposite

    static inline uint32_t from_id(struct CPUid *id)
    {
        return id->Stepping
             | id->Model << 4
             | id->FamilyID << 8
             | id->Type << 12
             | id->Reserved1 << 14
             | id->ExtendedModel << 16
             | id->ExtendedFamilyID << 20
             | id->Reserved2 << 28;
    }
    

提交回复
热议问题