Monster Hunter
Monster Hunter

Reputation: 866

array alignment of 3 bits

I have a struct that contains a 3-bit field.

struct A {
  unsigned char a:3;
};

I'd like to have an array of struct A that each element only takes 3 bits instead of a whole byte.

Is there anyway to do it?

Upvotes: 0

Views: 94

Answers (2)

Grantly
Grantly

Reputation: 2556

Your best way would be to store 24 bits in each struct, then you have 8 x 3 bit entities in each struct. You can use bitwise manipulation to access each entity of 3 bits within the struct of:

struct A {
  unsigned char a[3];
};

Then you have no wasted space when you create arrays, etc. However, you will waste any 3 bit entities that are not used, maximum 7 of them vs possible minimum of 0 (no wastage).

Upvotes: 3

SergeyA
SergeyA

Reputation: 62583

No, this is not possible. a takes 3 bits, but A would take at least sizeof(char).

By the way, this is exactly why you can have bit fields as struct members, but can't have bit variables - as, say, function local variables. Minimally addressable unit is one byte.

Upvotes: 1

Related Questions