Strange results when casting from double to integer

Hi,

I have a problem with the implementation of “overflow” when casting from
double to integer.

In my code, an angle was implemented as an integer, and the [-PI,PI] range
is mapped to the [INT_MIN, INT_MAX] range. So, thanks to the “overflow”, my
angle variables were always ranging between -PI and PI, automatically and at
no cost.

That “automatic modulo” is working perfectly on Windows (VC++) but not on
Neutrino RTP
If you try this code :

#define DBL_VALUE (1073741824.0) // INT_MAX / 2
double dbl_value = DBL_VALUE;
printf( “n1 = %d \n”, (int)(3.0DBL_VALUE) );
printf( “n2 = %d \n”, (int)(3.0
dbl_value) );
printf( “u1 = %d \n”, (unsigned int)(-DBL_VALUE) );
printf( “u2 = %d \n”, (unsigned int)(-dbl_value) );

On Windows (VC++), you will obtain the same expected results :
n1 = -1073741824
n2 = -1073741824
u1 = -1073741824
u2 = -1073741824

On Neutrino RTP (GCC), you will obtain this :
n1 = -1073741824
n2 = -2147483648 // ???
u1 = -1073741824
u2 = -1073741824

Why does the casting behave differently for constants and variables ?
Is there a way to have the same behaviour ?

Thanks a lot
Cyril OTHENIN-GIRARD.

You are relying on compiler and chip implementations here. This isn’t
safe. Note that you will also get different effects when you optimize.

Cyril OTHENIN-GIRARD <cothenin@bcisa.com> wrote:

Hi,

I have a problem with the implementation of “overflow” when casting from
double to integer.

In my code, an angle was implemented as an integer, and the [-PI,PI] range
is mapped to the [INT_MIN, INT_MAX] range. So, thanks to the “overflow”, my
angle variables were always ranging between -PI and PI, automatically and at
no cost.

That “automatic modulo” is working perfectly on Windows (VC++) but not on
Neutrino RTP
If you try this code :

#define DBL_VALUE (1073741824.0) // INT_MAX / 2
double dbl_value = DBL_VALUE;
printf( “n1 = %d \n”, (int)(3.0DBL_VALUE) );
printf( “n2 = %d \n”, (int)(3.0
dbl_value) );
printf( “u1 = %d \n”, (unsigned int)(-DBL_VALUE) );
printf( “u2 = %d \n”, (unsigned int)(-dbl_value) );

On Windows (VC++), you will obtain the same expected results :
n1 = -1073741824
n2 = -1073741824
u1 = -1073741824
u2 = -1073741824

On Neutrino RTP (GCC), you will obtain this :
n1 = -1073741824
n2 = -2147483648 // ???
u1 = -1073741824
u2 = -1073741824

Why does the casting behave differently for constants and variables ?
Is there a way to have the same behaviour ?

Thanks a lot
Cyril OTHENIN-GIRARD.


cburgess@qnx.com