Why is the sizeof a struct with bit fields not what I expected.
#include <iostream>
using namespace std;
struct test {
uint8_t x : 4;
uint16_t y : 8;
uint16_t z : 8;
};
struct test2 {
uint8_t x : 4;
uint16_t y : 10;
uint16_t z : 10;
};
int main()
{
cout << sizeof(test) << endl;
cout << sizeof(test2) << endl;
}
This prints 4 and 4.
I don't understand why both of these do not have a size of 3. Test has 4+8+8 bits which is 20 and Test2 has 4+10+10 bits which is 24 bits, both less than or equal to 24 bits/3 bytes. I know that if in Test I use uint_8
it would result in a size of 3 but for my actual use case I need Test2(4,10,10 bits). Why is this and is there a way to get this to 3 bytes?