0

I have a base class with a bitfield

enum Enum {
 ENUM1,
 ENUM2,
 ...
 ENUM8
};

struct Base {
  Enum type : 3;
};

I am inheriting a class

struct Derived : public Base {
 bool bf1 :  1;
 u32  bf2 : 19,
 u32  bf1 :  9;
};

I need to ensure that the memory space for the Derived class is 4 bytes (I have a 32-bit microcontroller), since there will be several inherited classes and they need to be serialized, and when unpacking by the 'type' field, understand how to process the remaining bit fields .

Is this method reliable? If not, how can we do it better?

My CLang compiler does package everything correctly, but I'm not sure about the reliability of this result.

5
  • 2
    Bitfields are implementation specific. It is hard to ensure what you want in a portable way, but if you know what is your CPU and compiler, I think your approach is OK. At least place a static_assert(sizeof(Derived)==4); in your code.
    – prapin
    Commented Jun 27 at 17:49
  • 6
    The standard gives no guarantees for this. You are in Implementation defined territory. Commented Jun 27 at 17:56
  • The underlying type of Enum is also implementation-defined, although not larger than int. You can fix the underlying type by writing e.g. enum Enum : int { /*...*/ };. And u32 is not a standard type. You must have defined it somewhere yourself or in a library. The standard type is named uint32_t. Commented Jun 27 at 18:06
  • 3
    Bitfields do not do what you think they do. The only ensure you have a variable that behaves like it has N number of bits (it doesn't promise much about how it is stored in memory). For real bitwise operations you will have to make a type of known size and use shifts and masks. And then don't use an enum, but just constexpr <some_type> bit1 = 0x01; in a namespace Commented Jun 27 at 18:09
  • Is this method reliable? Limited reliability. It's at the mercy of the compiler implementation, which can vary by platform or by compiler. I avoid it (because my code runs on a lot of different platforms), and code my bit twiddling explicitly. If not, how can we do it better? Do your own bit twiddling.
    – Eljay
    Commented Jun 27 at 20:18

0

Browse other questions tagged or ask your own question.