我使用这种形式的类型简化了对微处理器寄存器和其中的位字段的访问。
typedef union
{
uint8_t u8Byte; ///< REG_8 as unsigned byte
int8_t i8Byte; ///< REG_8 as signed byte
struct
{
unsigned b0:1; ///< Bit 0 of REG_8 type
unsigned b1:1; ///< Bit 1 of REG_8 type
unsigned b2:1; ///< Bit 2 of REG_8 type
unsigned b3:1; ///< Bit 3 of REG_8 type
unsigned b4:1; ///< Bit 4 of REG_8 type
unsigned b5:1; ///< Bit 5 of REG_8 type
unsigned b6:1; ///< Bit 6 of REG_8 type
unsigned b7:1; ///< Bit 7 of REG_8 type
};
} REG_8;不幸的是,sizeof(REG_8)返回2而不是预期的1。REG_16和REG_32的类似定义返回大小为2和4,就像预期的那样。sizeof(uint8_t)和sizeof(int8_t)按预期返回1。
该类型按预期工作。例如,
REG_8 a;
a.u8Byte = 4;给a.b2的值为1,因此不存在对齐问题。
删除struct给出的sizeof值为1,因此看起来存在填充问题,但如果是,为什么呢?
有人能解释一下吗?我正在使用微芯片XC16编译器(基于GCC)针对一个16位处理器.
发布于 2015-10-07 21:27:36
在您的机器上,可能相当大(无符号)=2,因此任何“无符号”位字段至少占用两个字节。用uint8_t替换未签名应该会使REG_8达到1。
也请参阅这个问题:How is the size of a struct with Bit Fields determined/measured?
https://stackoverflow.com/questions/33002535
复制相似问题