gpt4 book ai didi

c - 压缩结构位域与#define'd 位掩码

转载 作者:太空宇宙 更新时间:2023-11-04 08:53:16 27 4
gpt4 key购买 nike

我有一个 AVR 程序,它在一个静态状态变量中存储一组(通常少于 8 个)位标志(它包含在一个包含模块的各种其他状态字段的结构中)。

如果这样做效率更高或更低:

#define STATUS_ENABLED 0x01

struct DeviceState {
uint8_t status;
}

static struct DeviceState myState;

//and somewhere in the program...
myState.status |= STATUS_ENABLED;

或者用打包的位域来做:

struct DeviceState {
uint8_t enabled : 1;
}

static struct DeviceState myState;

//and somewhere in the program...
myState.enabled = 1; // could use TRUE/FALSE if defined

最佳答案

对于 avr-gcc 4.3.3,似乎在实现上没有区别:

#define STATUS_ENABLE

struct DeviceState {
uint8_t status;
uint8_t enabled : 1;
}

static struct DeviceState myState;

//and this code...
myState.status |= STATUS_ENABLED;
myState.enabled = 1;

生成以下汇编代码:

    myState.status |= STATUS_ENABLE;
00003746 LDS R24,0x20B5 Load direct from data space
00003748 ORI R24,0x01 Logical OR with immediate
00003749 STS 0x20B5,R24 Store direct to data space

myState.enabled = TRUE;
0000374B LDS R24,0x20B4 Load direct from data space
0000374D ORI R24,0x01 Logical OR with immediate
0000374E STS 0x20B4,R24 Store direct to data space

所以相同的指令(除了地址!)。

关于c - 压缩结构位域与#define'd 位掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18765630/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com