Look at this simple program :
#include <iostream>
using namespace std;
int main()
{
unsigned int i=0x3f800000;
float* p=(float*)(&i);
float f=*p;
cout<<f;
}
This is what I expect from the program:
f in output.f is the value that p is point to.p points to the value that is in the address of variable named i. (i.e. to the value of i)i is 0x3f800000So I expect to see the 0x3f800000in output, but It prints 1 instead. Why?
ap1019@sharifvm:~$ ./a.out
1
ap1019@sharifvm:~$
What you did is reinterpret_cast a pointer to int to pointer to float and retrieved a float value through the converted pointer.
In general, it's undefined behavior, but it so happened on your machine that int and float have the same size, and the bytes which represent int value 0x3f800000, also represent float value 1.
So I expect to see the
0x3f800000in output, but It prints1instead. Why?
Because 0x3f800000 has the bit pattern 00111111100000000000000000000000 that if read according to the IEEE 754 standard is representing the float 1.0

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With