c++carraysstructbit-packing

Specifying bit size of array elements in a struct


Now I have a struct looking like this:

struct Struct {
    uint8_t val1 : 2;
    uint8_t val2 : 2;
    uint8_t val3 : 2;
    uint8_t val4 : 2;
} __attribute__((packed));

Is there a way to make all the vals a single array? The point is not space taken, but the location of all the values: I need them to be in memory without padding, and each occupying 2 bits. It's not important to have array, any other data structure with simple access by index will be ok, and not matter if it's plain C or C++. Read/write performance is important - it should be same (similar to) as simple bit operations, which are used now for indexed access.

Update:

What I want exactly can be described as

struct Struct {
    uint8_t val[4] : 2;
} __attribute__((packed));

Solution

  • No, C only supports bitfields as structure members, and you cannot have arrays of them. I don't think you can do:

    struct twobit {
        uint8_t val : 2;
    } __attribute__((packed));
    

    and then do:

    struct twobit array[32];
    

    and expect array to consist of 32 2-bit integers, i.e. 8 bytes. A single char in memory cannot contain parts of different structs, I think. I don't have the paragraph and verse handy right now though.

    You're going to have to do it yourself, typically using macros and/or inline functions to do the indexing.