Struggling with packing bit-fields in C++ struct

  Kiến thức lập trình

I was trying to make a nicer type for working with packed data being sent to an LED driver IC. The format looks like this. It shows two possible formats, depending on the value of the Address bit. Note that the MSB is shown at the right, not the left, and should be the first bit shifted into the IC:

I tried to write a union type that would cover this, but it kept expanding to 5 bytes. So I settled on trying to just write this:

struct Color {
    uint8_t     ignore  :   1;
    uint8_t     address :   1;
    uint16_t    red     :   10;
    uint16_t    green   :   10;
    uint16_t    blue    :   10;

} __attribute__((packed));

Dumping the bytes in order from the start of the struct (on an M1 MacBook Pro, compiled with Clang, so little-endian) gives me:

Color c;
c.ignore = 1;
dump(&c, sizeof(c));

01 00 00 00 

I expected 80 00 00 00. If I put address and ignore at the end of the struct, I get 00 00 00 80, which is also unexpected.

Is it possible to write the type such that the bits are all packed into 4 bytes in the order expected? I realize there may also be an endianness issue in the assignment to the uint16_t values, but I think I can deal with that.