How to assign a value to a structure with bit fields?

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

error: conversion from 'uint32_t {aka unsigned int} to non-scalar type' main () :: a CPUID request was requested.

struct CPUIDregs
    {
       uint32_t EAXBuf;
    };
CPUIDregs CPUIDregsoutput;   


int main () {

 struct CPUID          
    {
          uint32_t   Stepping         : 4;         
          uint32_t   Model            : 4;        
          uint32_t   FamilyID         : 4;        
          uint32_t   Type             : 2;        
          uint32_t   Reserved1        : 2;         
          uint32_t   ExtendedModel    : 4;         
          uint32_t   ExtendedFamilyID : 8;          
          uint32_t   Reserved2        : 4;          
    };

    CPUID CPUIDoutput = CPUIDregsoutput.EAXBuf;

Do you have any ideas how to do this as soon as possible? Thanks

PS Of course, I have a more suitable EAX value in real code, but I think that does not affect it here.

+5
source share
4 answers

You should never rely on how the compiler poses your structure in memory. There are ways to do what you want with one task, but I will not recommend or tell you.

:

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

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

.

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;
}
+3

, - , :

*(reinterpret_cast<uint32_t *> (&CPUIDoutput)) = CPUIDregsoutput.EAXBuf;
+2

, , , RHS CPUID. , , struct .

, , , , . .

, , / .

+1

All Articles