How do I get these member members to fit in 3 bytes?
I have a structure that should not be more than 14 bytes in length, and at the moment I have 3 bytes left (11 bytes already taken). I need to add 3 members whose size ranges from 40 to 8188 id1 whose value ranges from 1 to 257 id2 whose value ranges from 1 to 254 So I
uint16_t size:13;
uint16_t id1:9;
uint8_t id2:8;
On the other hand, this would lead me to a 6 bit overkill. What are the other ways to get these 3 members to match 3 bytes? Id1 and Id2 should always be together.
source to share
It's impossible.
Logically speaking, the number of possible values ββis:
- 8148 different
size
s - 256 different
id1
s - 253 different
id2
s
This makes 8148 * 256 * 253 = 527729664 different value combinations. 2 ^ 24, that's all the possibilities you get for three bytes, that's only 16777216. Even if you combine all three numbers together, you can't do it.
You can fit into 29 bits as it is. Or you can limit the range of values ββfurther.
If there is more information about covariance - for example, "when id2
equal to one, size
always greater than 500", you can use that to compress more.
source to share
If the total size of the structure is 14 bytes, then there are two possibilities:
-
alignof(type) == 2
-
alignof(type) == 4
oralignof(type) == 8
It depends on the members declared in the previous 11 bytes. It cannot be 1 byte aligned since you already have a member that is 13 bits.
Now in the first case, you cannot find a solution to your problem. Not only because, therefore, there 13+9+8 > 3*8
is no room (and there is no workaround for this, see Shannon's first theorem ). But also the fact that if the structure is aligned on a 2 byte boundary, you cannot have a bit field that crosses the boundary (which is the case id1
, since 3 bits will be in a 2 byte group and the rest in others).
If the alignment is 4/8 bytes, there is no problem, since it takes 2 bytes to fill (so the effective size of the structure is 16 bytes), and you have a lot of free space.
source to share