Why does the sizes of these two structs differ?
#pragma pack(push, 1)
struct WordA
{
uint32_t address : 8;
uint32_t data : 20;
uint32_t sign : 1;
uint32_t stateMatrix : 2;
uint32_t parity : 1;
};
struct WordB
{
uint8_t address;
uint32_t data : 20;
uint8_t sign : 1;
uint8_t stateMatrix : 2;
uint8_t parity : 1;
};
#pragma pack(pop)
Somehow WordB
occupies 6 bytes instead of four, while WordA
occupies exactly 32 bits.
I assumed that given the sum of used bits inside a struct would yield both structs to be of the same size. Apparently I am wrong, but I cannot find an explanation why.
Bit fields page shows only examples when all of the struct members are of the same type, which is a case of WordA
.
Can anybody explain, why the sizes don't match and if it is according to the standard or implementation-defined?
Which of the following is not allowed? Explanation: None. 9. Bit fields can only be declared as part of a structure.
Arrays of bit fields, pointers to bit fields, and functions returning bit fields are not allowed. The optional declarator names the bit field. Bit fields can only be declared as part of a structure. The address-of operator (&) cannot be applied to bit-field components.
No, you can't. Bit field can only be used with integral type variables.
Bit-fields behave in much the same way, but whereas structs divide memory into pieces with well-known sizes, either primitive types or previously specified structures, bit-fields allow programmers to access groups of bits that are smaller than eight bits.
The type of a bit field can only be integral or enumeration type. A bit field cannot be a static data member . There are no bit field prvalues: lvalue-to-rvalue conversion always produces an object of the underlying type of the bit field.
Unions allow programmers to circumvent C++'s strong typing rules while bit-fields allow programmers to access the bits that encode the compressed information. Notice that there are a total of 16 bits in the "modes" bit-field above, the same number of bits as in a short integer.
The following properties of bit fields are implementation-defined : The value that results from assigning or initializing a signed bit field with a value out of range, or from incrementing a signed bit field past its range.
Why can't a bit field be split between different underlying types?
It can in the sense that standard allows it.
It wasn't because that's what the language implementer (or rather, the designer of the ABI) chose. This decision may have been preferred because it may make the program faster or the compiler easier to implement.
Here is the standard quote:
[class.bit]
... Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With