Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

...

Code Block
bgColor#ccccff
class WideSample {
  public static void main(String[] args) {
    int big = 1234567890;
                  
    // The significand can store at most 23 bits
    if(Integer.highestOneBit(big) >> Math.pow(2, 23)) { 
      throw new ArithmeticException(""Insufficient precision"");	
    }

    float approx = big;
    System.out.println(big - (int)approx);  // Prints zero when no precision is lost
  }
}

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C Secure Coding Standard as FLP36-C. Beware of precision loss when converting integral types to floating point.

...

INT31-J. Do not rely on the write() method to output integers outside the range 0 to 255            06. Integers (INT)            INT34-J. Perform explicit range checking to ensure integer operations do not overflow