...
The following table presents the rules for narrowing primitive conversions of integer types. In the table, for an integer type T
, n
represents the number of bits used to represent the resulting type T
(precision).
From | To | Description | Possible Resulting Errors |
---|---|---|---|
Signed integer | Integral type | Keeps only | Lost or misinterpreted data |
| Integral type | Keeps only | Magnitude error; negative number even though |
When integers are cast to narrower data types, the magnitude of the numeric value and the corresponding sign can be affected. Consequently, data can be lost or misinterpreted.
...
Casting a numeric value to a narrower type can result in information loss related to the sign and magnitude of the numeric value. As a result, data can be misrepresented or interpreted incorrectly.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM12-J | Low | Unlikely | Medium | P2 | L3 |
Automated Detection
Automated detection of narrowing conversions on integral types is straightforward. Determining whether such conversions correctly reflect the intent of the programmer is infeasible in the general case. Heuristic warnings could be useful.
Tool | Version | Checker | Description |
---|---|---|---|
Parasoft Jtest |
|
|
| PB.NUM.CLP |
Do not cast primitive data types to lower precision |
Related Guidelines
INT31-C. Ensure that integer conversions do not result in lost or misinterpreted data | |
Numeric Conversion Errors [FLC] | |
CWE-681, Incorrect Conversion between Numeric Types |
Bibliography
[JLS 2005] | §4.2.1, "Integral Types and Values" |
[Seacord 2015] |
...
...