Versions Compared

Key

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

Although many common implementations use a two's complement representation of signed integers, the C99 standard declares this as C Standard declares such use as implementation-defined, and allows all of the following representations:

  • Sign and magnitude
  • Two's complement
  • OnesOne's complement

This is a specific example of MSC14-C. Do not introduce unnecessary platform dependencies.

Noncompliant Code Example

One way to check whether a number is even or odd is to examine the least significant bit. This will give inconsistent results, but the results will be inconsistent. Specifically, this example will give gives unexpected behavior on all onesone's complement implementations.:

Code Block
bgColor#ffcccc
langc

int value;

if (scanf("%d", &value) == 1) {
  if (value & 0x1 =!= 10) {
    /* doTake somethingaction if value is odd */
  }
}

Compliant Solution

The same thing can be achieved compliantly using the modulo operator.:

Code Block
bgColor#ccccff
langc

int value;

if (scanf("%d", &value) == 1) {
  if (value % 2 != 0) {
    /* Take action if value is odd */
  }
}

Compliant Solution

Using bitwise operators is safe on unsigned integers:

Code Block
bgColor#ccccff
languagec
unsigned int value;

if (scanf("%u", &value) == 1) {
  if (value & 0x1 != 0) {
    /* doTake somethingaction if value is odd */
  }
}

Risk Assessment

Incorrect assumptions about integer representation can lead to execution of unintended code branches and other unexpected behavior.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

 

INT16-C

medium

Medium

unlikely

Unlikely

medium

High

P4

L3

References

P2

L3

Automated Detection

Tool

Version

Checker

Description

Astrée
Include Page
Astrée_V
Astrée_V
bitop-type
Partially checked
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C2940, C2945 

DF2941, DF2942, DF2943, DF2946, DF2947, DF2948


LDRA tool suite
Include Page
LDRA_V
LDRA_V
50 S, 120 SPartially Implemented
Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V
CERT_C-INT16-a
Bitwise operators shall only be applied to operands of unsigned underlying type
PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

502, 2704, 9088

Partially supported: reports bitwise not of signed quantity, declaration of named signed single-bit bitfields, and negation of the minimum negative integer

RuleChecker

Include Page
RuleChecker_V
RuleChecker_V

bitop-type
Partially checked


...

Image Added Image Added Image Added Wiki Markup\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.2.6.2