首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么这个ty胡枝子给出的值比预期的要大?

为什么这个ty胡枝子给出的值比预期的要大?
EN

Stack Overflow用户
提问于 2015-10-07 21:14:40
回答 1查看 688关注 0票数 0

我使用这种形式的类型简化了对微处理器寄存器和其中的位字段的访问。

代码语言:javascript
复制
  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。

该类型按预期工作。例如,

代码语言:javascript
复制
REG_8  a;
a.u8Byte = 4;

a.b2的值为1,因此不存在对齐问题。

删除struct给出的sizeof值为1,因此看起来存在填充问题,但如果是,为什么呢?

有人能解释一下吗?我正在使用微芯片XC16编译器(基于GCC)针对一个16位处理器.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-07 21:27:36

在您的机器上,可能相当大(无符号)=2,因此任何“无符号”位字段至少占用两个字节。用uint8_t替换未签名应该会使REG_8达到1。

也请参阅这个问题:How is the size of a struct with Bit Fields determined/measured?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33002535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档