Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: JPCERT comments

...

1. When converting a floating-point value to an int or long and the value is a NaN, an int or long, a zero value is produced. Otherwise, if the value is not infinity, it is rounded towards zero to an integer value V:

...

The minimum and maximum float values are converted to minimum and maximum int values (0x80000000 and 0x7fffffff, respectively). The resulting short values are the lower 16 bits of these values (0x0000 and 0xffff). The resulting final values (0 and -1) could be unexpected.

...

This compliant solution range-checks both the i and j variables before converting to the resulting integer type. Since both values are out of the valid range for a short, this code will always throw an ArithmeticException.

Code Block
bgColor#ccccff
float i = Float.MIN_VALUE;
float j = Float.MAX_VALUE;
if ((i < Short.MIN_VALUE) || (i > Short.MAX_VALUE) ||
    (j < Short.MIN_VALUE) || (j > Short.MAX_VALUE)) {
  throw new ArithmeticException ("Value is out of range");    
}

short b = (short) i;
short c = (short) j;
//other operations

...

Perform range checks on both i and j variables before proceeding with the conversions. Since both values are out of the valid range for a short, this code will always throw an ArithmeticException.

Code Block
bgColor#ccccff
double i = Double.MIN_VALUE;
double j = Double.MAX_VALUE;
if ((i < Float.MIN_VALUE) || (i > Float.MAX_VALUE) ||
    (j < Float.MIN_VALUE) || (j > Float.MAX_VALUE)) {
  throw new ArithmeticException ("Value is out of range");    
}

float b = (float) i;
float c = (float) j;
//other operations

...

The CERT C Secure Coding Standard

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

The CERT C++ Secure Coding Standard

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="d993bf0ba29f9aa0-3ee9c72c-4e904e78-8456a6e6-b751df6c8813553ee2eab7f9"><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>

MITRE CWE

CWE ID 681, "Incorrect Conversion between Numeric Types"

 

CWE ID 197, "Numeric Truncation Error"

...