PPC/Intel difference for out-of-range double -> int conversion
PPC/Intel difference for out-of-range double -> int conversion
- Subject: PPC/Intel difference for out-of-range double -> int conversion
- From: Robert Purves <email@hidden>
- Date: Fri, 23 May 2008 07:16:01 +1200
While investigating a bug in my app, I found mistaken assumptions
about the interconvertibility of 32-bit integers and doubles. In
particular, the results of out-of-range conversion can differ between
ppc and i386.
$ cat test.c
#include <stdio.h>
#include <stdint.h>
double Double4294967295( void )
{
return 4294967295.0;
}
double DoubleMinus1( void )
{
return -1.0;
}
int main( void )
{
int32_t ival;
uint32_t uval;
ival = Double4294967295();
uval = DoubleMinus1();
printf( "%d %u\n", ival, uval );
return 0;
}
$ gcc test.c -arch ppc && ./a.out
2147483647 4294967295
$ gcc test.c -arch i386 && ./a.out
-2147483648 0
[Q1] Do these startling differences occur because the results are
'undefined' in the C standard, or because they are 'implementation-
dependent'?
By trial and error, I obtained the desired results (-1 and 4294967295,
independent of architecture) by casting to an intermediate 64-bit form:
ival = (int64_t)Double4294967295();
uval = (int64_t)DoubleMinus1();
$ gcc test.c -arch ppc && ./a.out
-1 4294967295
$ gcc test.c -arch i386 && ./a.out
-1 4294967295
[Q2] Does the cast (int64_t) make the results safe (that is, neither
undefined nor implementation-dependent)?
Robert P.
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden