应该怎么写呢?

2019-07-20 15:37发布

union {
       struct {
          unsigned b0:1;
          unsigned b1:1;
          unsigned b2:1;
          unsigned b3:1;
          unsigned b4:1;
          unsigned b5:1;
          unsigned b6:1;
          unsigned b7:1;
          }oneBit;
         unsigned char allBits;
        } myFlag;
#define fast    myFlag.oneBit.b0
#define mid     myFlag.oneBit.b1
#define slow    myFlag.oneBit.b2
#define flow    myFlag.oneBit.b3
#define voice   myFlag.oneBit.b4
#define pause   myFlag.oneBit.b5
#define white   myFlag.oneBit.b6
#define on_off  myFlag.oneBit.b7
#define mark    myFlag.allBits
上面的语句在PICC中编译出来每一个占一个位,但在KEIL C中编译出来怎么占一个字节啊?如果在在KEIL C 中要实现如上功能,应该怎么写呢?
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
该问题目前已经被作者或者管理员关闭, 无法添加新回复
16条回答
heweibig
1楼-- · 2019-07-20 15:38
 精彩回答 2  元偷偷看……
wuhany
2楼-- · 2019-07-20 18:30
 精彩回答 2  元偷偷看……
wuhany
3楼-- · 2019-07-20 21:28
这个不能怪Keil,是C标准规定了位域是2字节对齐的……也就是说就算你只定义了1bit的位域,它也要占用2字节,其它的15bit就这么空着……不信试一下以下代码:
typedef struct
{
         unsigned b0:1;
         unsigned b1:1;
         unsigned b2:1;
         unsigned b3:1;
         unsigned b4:1;
         unsigned b5:1;
         unsigned b6:1;
         unsigned b7:1;
}oneBitStructs;
typedef union
{
         oneBitStructs oneBit;
//        unsigned char allBits;
}myFlag;

myFlag flag;
void main(void)
{
         int size = sizeof(myFlag);
         size = sizeof(oneBitStructs);
         while(1)
                 ;
}
优化级别设为0
单步调试过程可以看到myFlag这个联合体占用了2字节,结构体oneBitStructs也是一样
dengdc
4楼-- · 2019-07-20 22:20
是啊,位域能不用就最好不要用,否则移植、通信会带来很多麻烦
jiaxw
5楼-- · 2019-07-21 04:19
 精彩回答 2  元偷偷看……
jiahy
6楼-- · 2019-07-21 07:08
 精彩回答 2  元偷偷看……

一周热门 更多>