Search code examples
cmisra

MISRA: Bitwise operation on signed integer


I have this error according to MISRA rules : bitwise operation may not be performed on signed integers.

    typedef unsigned __int8   gUBYTE;

    typedef gUBYTE gBORDER;
    enum {
        gbrLEFT     = 0x01,
        gbrTOP      = 0x02,
        gbrRIGHT    = 0x04,
        gbrBOTTOM   = 0x08,
        gbrALL      = gbrLEFT | gbrTOP | gbrRIGHT | gbrBOTTOM
    };

how could I solve this error ?


Solution

  • Change:

    gbrALL      = gbrLEFT | gbrTOP | gbrRIGHT | gbrBOTTOM
    

    to:

    gbrALL      = gbrLEFT + gbrTOP + gbrRIGHT + gbrBOTTOM
    

    This solves the problem in this particular expression. Later in the code, you could have expressions such as x & gbrLEFT, and this might also be flagged as a bitwise operation on a signed integer. However, if x is of type gUBYTE, it is unsigned. On the other hand, it will be promoted to an int, and then x & gbrLEFT is technically an operation on signed integers. On the other other hand, it would seem this would be a problem for a MISRA-analyzer; code might perform a completely safe bitwise operation on two unsigned objects which are promoted to signed int, thus triggering a warning from the analyzer. So it seems a good analyzer should recognize that the underlying objects are safe for the bitwise operation. (This applies to many bitwise operations. Some, such as ~ might be unsafe if applied to an unsigned object that has been promoted to int, depending on the C implementation and other context.)

    Is this so? If so, then fixing up the one expression shown above might suffice.