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, it is frequently the case that bitwise operations are 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.

...

The typedef name uintN_t designates an unsigned integer type with width N. Consequently, uint32_t denotes an unsigned integer type with a width of exactly 32 bits. Bitmaps are normally declared as unsigned.

Non-Compliant Code Example (

...

Left Shift)

In this non-compliant code example, both bit manipulation and arithmetic manipulation are performed on the integer type x. The result is a (prematurely) optimized statement that assigns 5x + 1 to x for implementations where integers are represented as two's complement values.

...

Although this is a valid manipulation, the result of the shift depends on the underlying representation of the integer type and is consequently implementation-defined. Additionally, the readability of the code is reduced.

Compliant Solution (

...

Left Shift)

In this compliant solution, the assignment statement is modified to reflect the arithmetic nature of x, resulting in a clearer indication of the programmer's intentions.

...

A reviewer may now recognize that the operation should be checked for integer overflow. This might not have been apparent in the original, non-compliant code example.

Non-Compliant Code Example (

...

Right Shift)

In this non-compliant code example, the programmer prematurely optimizes code by replacing a division with a right shift.

...

For example, if the internal representation of x is 0xFFFF FFCE (two's complement), an arithmetic shift results in 0xFFFF FFF3 (-13 in two's complement), while a logical shift results in 0x3FFF FFF3 (1 073 741 811 in two's complement).

Compliant Solution (

...

Right Shift)

In this compliant solution, the right shift is replaced by division.

...

Performing bit manipulation and arithmetic operations on the same variable obscures the programmers programmer's intentions and reduces readability. This in turn makes it more difficult for a security auditor or maintainer to determine which checks must be performed to eliminate security flaws and ensure data integrity.

...