Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Avoid performing bitwise and arithmetic operations on the same data. In particular, bitwise operations are frequently performed on arithmetic values as a form of premature optimization. Bitwise operators include the unary operator ~ and the binary operators <<, >>, &, ^, and |. Although such operations are valid and will compile, they can reduce code readability. Declaring a variable as containing a numeric value or a bitmap makes the programmer's intentions clearer and the code more maintainable.

Bitmapped types may be defined to further separate bit collections from numeric types. This Doing so may make it easier to verify that bitwise operations are performed only on variables that represent bitmaps.

Code Block
typedef uint32_t bitmap32_t;
bitmap32_t x = 0x000007f3;

x = (x << 2) | 3; /* shiftsShifts in two 1-bits from the right */

...

Although this code is likely to perform the division correctly, it is not guaranteed to. If x has a signed type and a negative value, the operation is implementation-defined and can be implemented as either an arithmetic shift or a logical shift. In the event of a logical shift, if the integer is represented in either one's complement or two's complement form, the most significant bit (which controls the sign for both representations) will be set to zero. This will cause 0, causing a once negative number to become a possibly very large, positive number. For more details, see INT13-C. Use bitwise operators only on unsigned operands.

...

Tool

Version

Checker

Description

Compass/ROSE

 

 

Can detect violations of this recommendation. However, it can detect only detect those violations where both bitwise and arithmetic operators are used in the same expression

Fortify SCA

5.0

 

Can detect violations of this recommendation with the CERT C Rule Pack

LDRA tool suite

Include Page
LDRA_V
LDRA_V

585 S

Fully implemented

...