I am having an interesting problem when casting from double to an unsigned short int as shown in the following example:.
#include<stdio.h>
int main()
{
unsigned short int ius;
unsigned short int ous;
short int is;
ius = 52536;
is = (short int) ((double)(ius));
ous = (unsigned short int) is;
printf("ius = %hu\n", ius);
printf("is = %d\n", is);
printf("ous = %hu\n", ous);
}
Using a Sun CC compiler and Microsoft Visual C++ for 32-bit, the above code generates:
ius = 52536
is = -13000
ous = 52536
which is as I would expect. The two's complement of 52536 is -13000.
However, when compied using gcc (version 3.2.3, also confirmed with gcc 4.4.1) with the -m32 option specifed, the code produces:
ius = 52536
is = -32768
ous = 32768
Is this a bug with gcc? Also, if I don't cast ius to (double) before casting to (short int), I get what I expect. Can anyone explain?
Thanks!
Note: this problem popped up in some code I am trying to port from Solaris to Linux. The code includes the following macro:
#define REAL_TO_SHORT_BIT_TYPE(X) ((unsigned short int) ((short int) ((double) (x))))