Search code examples
cbit-fieldsmisrauint8t

How to assign bitfield variable to uint8_t variable without violating MISRA rules?


I have a typedef struct named Character.

typedef struct {
    unsigned int a : 1;
    unsigned int b : 1;
    unsigned int c : 1;
    unsigned int d : 1;
    unsigned int o : 1;
    unsigned int p : 1;
    unsigned int q : 1;
    unsigned int x : 1;
} Character;

static Character tempChar;

void writeVar(const uint8_t *pData)
{
    tempChar.a = pData[0] >> 5;
    ...
}

When I try to assign an uin8_t variable (with value 0 or 1) to one of these bitfields, I got a violation to MISRA rule 10.6 which states that:

The value of a composite expression shall not be assigned to an object with wider essential type

Is there a way to assign a bit-field to uint8_t without violating MISRA C?


Solution

  • Both operands in the expression pData[0] >> 5 will, if needed, be promoted to int (it will happen for pData[0]).

    And the result of the expression is an int.

    Both the promotion and the conversion from int to unsigned int, while perfectly valid and fine in normal cases, is enough for the very strict MISRA to complain.

    Simple solution (as shown in comments) is to explicitly convert pData[0] to unsigned int using casting.