Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(int)4294967295.0 = 2147483647?

Tags:

c

Example code:

#include <stdio.h>

int main() {
    printf("%d", (int)4294967295.0);
    return 0;
}

This prints 2147483647 on the codepad (http://codepad.org/yDCqFdTT) and -2147483648 on my vs2012 settings. Expected -1. Converting 4294967295.0 to unsigned integer correctly yields -1, however.

What's happening? How can I safely convert my double to int? This kind of error is way beyond the range of rounding error.

like image 910
whyask37 Avatar asked Feb 12 '23 03:02

whyask37


1 Answers

According to draft N1256 (C99) §6.3.1.4, you are invoking undefined behavior:

6.3.1.4 Real floating and integer

  1. When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.50)

  2. When a value of integer type is converted to a real floating type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined.

50) The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, the range of portable real floating values is (−1, Utype_MAX+1).

like image 85
icktoofay Avatar answered Feb 15 '23 11:02

icktoofay