0

I have an AVR program which stores a set (usually less than 8) bit flags in a static status variable (which is contained inside a struct holding various other state fields of the module).

if it more or less efficient to do it like this:

#define STATUS_ENABLED 0x01

struct DeviceState {
    uint8_t status;
}

static struct DeviceState myState;

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

Or do it with a packed bitfield:

struct DeviceState {
    uint8_t enabled : 1;
}

static struct DeviceState myState;

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

3 回答 3

3

使用 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 

所以同样的指令(地址除外!)。

于 2013-09-12T13:25:55.463 回答
2

位字段版本是不可移植的,并且位的实际位置定义不明确。除此之外,应该没有区别。因此,请使用前一个版本,因为它是 100% 可移植的。

于 2013-09-12T13:33:09.567 回答
-2

打包位域允许您在 8 位内存空间中存储其他变量,因此如果您要向 DeviceStatus 添加更多变量,则内存效率会更高。

于 2013-09-13T18:08:35.863 回答