Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-874

Bitwise operators should not be applied to signed operands

    XMLWordPrintable

    Details

    • Message:
      Do not apply "X" bitwise operator to a signed operand.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Covered Languages:
      C, C++, Objective-C
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      30min
    • CERT:
      INT13-C.
    • CWE:
      CWE-682
    • MISRA C 2004:
      12.7
    • MISRA C 2012:
      10.1
    • MISRA C++ 2008:
      5-0-21
    • CPPCheck:
      charBitOp
    • PC-Lint:
      701, 1701, 702, 1702, 703, 1703, 704, 1704, 9030

      Description

      Most built-in bitwise operators (~, >>, >>=, &, &=, {}, =, |, and |=) have implementation-dependent results when performed on signed operands, and bitwise left shift (<< and <<=) has undefined behavior when performed on negative operands. Therefore bitwise operations should not be performed on signed operands.

      Noncompliant Code Example

      if ( ( uint16_a & int16_b ) == 0x1234U ) 
      if ( ~int16_a == 0x1234U ) 
      

      Compliant Solution

      if ( ( uint16_a | uint16_b ) == 0x1234U ) 
      if ( ~uint16_a == 0x1234U )
      

      Exceptions

      When used as bit flags, it is acceptable to use preprocessor macros as arguments to the & and | operators even if the value is not explicitly declared as unsigned.

      fd = open(file_name, UO_WRONLY | UO_CREAT | UO_EXCL | UO_TRUNC, 0600);
      

      If the right-side operand to a shift operator is known at compile time, it is acceptable for the value to be represented with a signed type provided it is positive.

      #define SHIFT 24
      foo = 15u >> SHIFT;
      

      See

      • MISRA C:2004, 12.7 - Bitwise operators shall not be applied to operands whose underlying type is signed
      • MISRA C++:2008, 5-0-21 - Bitwise operators shall only be applied to operands of unsigned underlying type
      • MISRA C:2012, 10.1 - Operands shall not be of an inappropriate essential type
      • CERT, INT13-C. - Use bitwise operators only on unsigned operands
      • MITRE, CWE-682 - Incorrect Calculation

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              Anonymous Anonymous
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: