Conversions of numeric types to narrower types can result in lost or misinterpreted data if the value of the wider type is outside the range of values of the narrower type. Therefore, all narrowing conversions must be guaranteed safe by range-checking the value before conversion.
There are 22 possible narrowing primitive conversions in Java. According to the Java Language Specification, §5.1.3, "Narrowing Primitive Conversions" ,
...
NUM12-EX0: Java's narrowing conversions are both well-defined and portable. Knowledgeable programmers can intentionally apply such conversions The effects of narrowing on integral types can be easily reproduced in code; however the effects of narrowing on floating-point types, and between floating-point types and integral types cannot be easily represented. Knowledgeable programmers may intentionally apply narrowing conversions involving floating-point types in contexts where their output is both expected and reasonable. Consequently, narrowing conversions are permitted when the code contains comments that document both the use of narrowing conversions and that the potential for truncation has been anticipated. A suitable comment might read: "// Deliberate narrowing cast of i; possible truncation OK"
This exception does not permit narrowing conversions with no range-checking among integral types. The following code example demonstrates how to perform explicit narrowing from a long
to an int
where range-checking is not required.
Code Block | ||
---|---|---|
| ||
long value = /* initialize */;
int i = (int) (value % 0x100000000); // 2^32
|
The range-checking is unnecessary because the truncation that is normally implicit in a narrowing conversion is made explicit. The compiler will optimize the operation away; hence it incurs no performance penalty.
Similar operations may be used for converting to other integral types.
Risk Assessment
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.
...
INT31-C. Ensure that integer conversions do not result in lost or misinterpreted data | ||||
| FLP34-C. Ensure that floating point conversions are within range of the new type | |||
INT31-CPP. Ensure that integer conversions do not result in lost or misinterpreted data | ||||
| FLP34-CPP. Ensure that floating point conversions are within range of the new type | |||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f158dd3272b8b470-4c49b233-46ad401f-9f61bd47-6cd2aabd70433cd02f29d01b"><ac:plain-text-body><![CDATA[ | [ISO/IEC TR 24772:2010 | http://www.aitcnet.org/isai/] | "Numeric Conversion Errors [FLC]" | ]]></ac:plain-text-body></ac:structured-macro> |
CWE ID 681, "Incorrect Conversion between Numeric Types" | ||||
| CWE ID 197, "Numeric Truncation Error" |
...