You can declare a bit field as a _Bool (C), bool (C++), char, signed
char, unsigned char, short, unsigned
short, int, unsigned int, long, unsigned
long, long long, or unsigned long
long data type. The alignment of a bit field depends
on its base type and the compilation mode (32-bit or 64-bit).
The length
of a bit field cannot exceed the length of its base type. In extended
mode, you can use the sizeof operator on a bit field. The sizeof operator
on a bit field always returns the size of the base type.
The length of a bit field can exceed the length of its base
type, but the remaining bits are used to pad the field, and do not
actually store any value.
However, alignment rules for aggregates containing bit fields are
different depending on the alignment mode in effect. These rules are
described below.
Rules for Linux® PowerPC® alignment
- Bit fields are allocated from a bit field container. The size
of this container is determined by the declared type of the bit field.
For example, a char bit field uses an 8-bit container,
an int bit field uses 32 bits, and so on. The container
must be large enough to contain the bit field, as the bit field will
not be split across containers.
- Containers are aligned in the aggregate as if they start on a
natural boundary for that type of container. Bit fields are not necessarily
allocated at the start of the container.
- If a zero-length bit field is the first member of an aggregate,
it has no effect on the alignment of the aggregate and is overlapped
by the next data member. If a zero-length bit field is a non-first
member of the aggregate, it pads to the next alignment boundary determined
by its base declared type but does not affect the alignment of the
aggregate.
- Unnamed bit fields do not affect the alignment of the aggregate.
Rules for bit-packed alignment
- Bit fields have an alignment of 1 byte, and are packed with no
default padding between bit fields.
- A zero-length bit field causes the next member to start at the
next byte boundary. If the zero-length bit field is already at a byte
boundary, the next member starts at this boundary. A non-bit field
member that follows a bit field is aligned on the next byte boundary.
Example of bit-packed alignment
#pragma options align=bit_packed
struct {
int a : 8;
int b : 10;
int c : 12;
int d : 4;
int e : 3;
int : 0;
int f : 1;
char g;
} A;
pragma options align=reset
The size of A is
7 bytes. The alignment of A is 1 byte. The layout
of A is:
| Member name |
Byte offset |
Bit offset |
| a |
0 |
0 |
| b |
1 |
0 |
| c |
2 |
2 |
| d |
3 |
6 |
| e |
4 |
2 |
| f |
5 |
0 |
| g |
6 |
0 |