Be Careful When Using Bit Field

Below illustration is based on MSP430, IAR. See the implementation below.

typedef struct
{
    uint8_t groupAddress                :4;     //group address
    uint8_t pointAddress                :3;     //point address
    uint8_t deviceType                  :1;     //device type;
}DeviceAddressS;  

gDeviceAddress.groupAddress = address >> 3;
gDeviceAddress.pointAddress = address & 0x7;

Let’s check the assemble code, there are total 26 execution codes and 28 execution codes for two lines C source code.

If we don’t use the bit field, what will be happened?

typedef struct
{
    uint8_t pointAddress;                       //point address
    uint8_t groupAddress;                       //group address
    uint8_t deviceType;                         //device type;
}DeviceAddressS;  
gDeviceAddress.groupAddress =  address >> 3;
gDeviceAddress.pointAddress = (address & 0x7);

Checking the assemble code again, there are total 10 execution codes and 12 execution codes.

So, the rule is that “be careful when using bit field”. Do you really has no enough space? In fact, if you don’t have enough space, the MCU performance is low, so don’t use bit field normally. If you real want to use it, using union and assigning whole value at the same time, see example below.

typedef union
{
  uint8_t value;
  struct
  {
    uint8_t pointAddress                :3;     //point address
    uint8_t groupAddress                :5;     //group address
  }bitFields;
}AddressU;

void AddressTest(void)
{
   uint8_t adddress = 255;
   AddressU temp;
   temp.value =  adddress;
   temp.value |= (adddress & 0x7);
}

It has a good performance.

Note that, they have same performance when reading for bit field or non-bit field.

猜你喜欢

转载自www.cnblogs.com/zjbfvfv/p/9122090.html