Search code examples
c++bit-fieldscpuid

Packing an int into a bitfield in C++


I'm converting some code from ASM to C++, the ASM simply looks like so:

mov dword ptr miscStruct, eax

the Struct looks like:

struct miscStruct_s {
  uLong brandID     : 8,
  chunks            : 8,
  //etc
} miscStruct;

Is there an easy one-two line way to fill the struct in C++? So far I am using:

miscStruct.brandID = Info[0] & 0xff; //Info[0] has the same data as eax in the ASM sample.
miscStruct.chunks = ((Info[0] >> 8) & 0xff);

That works fine and all, but I have to fill some 9-10 of these bitfield structs, some of them have 30 odd fields. So doing it this way ends up turning 10 lines of code into 100+ which obviously is not so great.

So is there a simple, clean way of replicating the ASM in C++?

I of course tried "miscStruct = CPUInfo[0];" but C++ doesn't like that unfortunately. :(

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int'

..And I can't edit the struct.


Solution

  • The literal translation of the assembler instruction is this:

    miscStruct=*(miscStruct_s *)&Info[0];
    

    The casts are needed because C++ is a type-safe language, whereas assembler isn't, but the copying semantics are identical.