首先,有可能做到吗?如果是,我在下面的声明中做错了什么?
struct mybitfields
{
uint8_t a : 4;
uint16_t c : 12;
} test;
Although what you are doing is possible, it is not portable: C99 standard says that bit-field base type must be a _Bool
, signed int
, or unsigned int
, allowing implementation-defined types to be used with bit-fields (C90 requires a signed on an unsigned int
as bit-field's base type; no other types are allowed).
See this answer for references to appropriate chapters of the C99 and C90 standards.
If your goal is to define a struct
of bit-fields of size that is smaller than an unsigned int
, you would be better off using bit shifts for portability.
Your code will be accepted by most compilers, but strictly speaking the base type of a bitfield must be a (signed / unsigned) int
.
uint8_t
is a typedef for unsigned char
, and uint16_t
is probably a typedef for unsigned short
, and bitfields made from these types are non-conforming.