P
Piotrne
Hi,
I have a strange problem with casting addresses to different
types. I have a float variable. The sequence of 4 bytes
representing its value should be copied to an int
(of the same size like float: 4 bytes) and then back
to the float variable. Example:
#include <stdio.h>
int main(int argc, char **argv)
{
float x = 4.3;
int y;
y = *(int*)&x; /* copying of 4 bytes to int */
x = *(float*)&y; /* and back to float */
printf("x=%f\n",x); /* 4.3 expected here */
printf("y=%d\n",y);
return 0;
}
I have compiled this example in Linux, using gcc 4.1.1, with
different optimization options. Here are the results:
$ gcc cast2.c
$ ./a.out
x=4.300000
y=1082759578
$ gcc -O2 cast2.c
$ ./a.out
x=-167393728255558576456059409056680378368.000000
y=134513634
The first result is correct, but what happened to the second?
Probably addresses have been shifted for some reason. But such
constructions seem to be an elementary property of the C language,
and they don’t work...
Regards
Piotr
I have a strange problem with casting addresses to different
types. I have a float variable. The sequence of 4 bytes
representing its value should be copied to an int
(of the same size like float: 4 bytes) and then back
to the float variable. Example:
#include <stdio.h>
int main(int argc, char **argv)
{
float x = 4.3;
int y;
y = *(int*)&x; /* copying of 4 bytes to int */
x = *(float*)&y; /* and back to float */
printf("x=%f\n",x); /* 4.3 expected here */
printf("y=%d\n",y);
return 0;
}
I have compiled this example in Linux, using gcc 4.1.1, with
different optimization options. Here are the results:
$ gcc cast2.c
$ ./a.out
x=4.300000
y=1082759578
$ gcc -O2 cast2.c
$ ./a.out
x=-167393728255558576456059409056680378368.000000
y=134513634
The first result is correct, but what happened to the second?
Probably addresses have been shifted for some reason. But such
constructions seem to be an elementary property of the C language,
and they don’t work...
Regards
Piotr