CertC-EXP14ΒΆ
Beware of integer promotion when performing bitwise operations on integer types smaller than int
Required inputs: IR
Deprecated
This guideline has been deprecated by
Integer types smaller than int are promoted when an operation is performed on them. If all values of the original type can be represented as an int , the value of the smaller type is converted to an int ; otherwise, it is converted to an unsigned int (see INT02-C. Understand integer conversion rules ). If the conversion is to a wider type, the original value is zero-extended for unsigned values or sign-extended for signed types. Consequently, bitwise operations on integer types smaller than int may have unexpected results.
Noncompliant Code Example
This noncompliant code example demonstrates how performing bitwise operations on integer types smaller than int may have unexpected results.
uint8_t port = 0x5a; uint8_t result_8 = ( ~port ) >> 4; |
In this example, a bitwise complement of port is first computed and then shifted 4 bits to the right. If both of these operations are performed on an 8-bit unsigned integer, then result_8 will have the value 0x0a . However, port is first promoted to a signed int , with the following results (on a typical architecture where type int is 32 bits wide):
| Expression | Type | Value | Notes |
|---|---|---|---|
port |
uint8_t |
0x5a |
|
~port |
int |
0xffffffa5 |
|
~port >> 4 |
int |
0x0ffffffa |
Whether or not value is negative is implementation-defined. |
result_8 |
uint8_t |
0xfa |
|
Compliant Solution
In this compliant solution, the bitwise complement of port is converted back to 8 bits. Consequently, result_8 is assigned the expected value of 0x0aU .
uint8_t port = 0x5a; uint8_t result_8 = (uint8_t) (~port) >> 4; |
Risk Assessment
Bitwise operations on shorts and chars can produce incorrect data.
| Recommendation | Severity | Likelihood | Detectable | Repairable | Priority | Level |
|---|---|---|---|---|---|---|
| EXP14-C | low | likely | No | No | P3 | L3 |
Related Guidelines
| SEI CERT C++ Coding Standard | VOID EXP15-CPP. Beware of integer promotion when performing bitwise operations on chars or shorts |
| MISRA-C | Rule 10.5 |
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
bitop_small_without_cast |
Bitwise operator requires cast to underlying type on result |
None |
False |
Options
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
This rule has no individual options.