Reputation: 6116
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 0x3f800000
So I expect to see the 0x3f800000
in output, but It prints 1
instead. Why?
ap1019@sharifvm:~$ ./a.out
1
ap1019@sharifvm:~$
Upvotes: 2
Views: 2483
Reputation: 234685
Don't expect anything from this code. The behaviour of (float*)(&i);
is undefined as the pointer types are unrelated.
float
and int
might not even be the same size. And you might be working on an architecture that stores float
and int
in entirely separate locations in memory. It's even possible that sizeof(float*)
is not the same as sizeof(int*)
. Unlikely, but possible.
Upvotes: 1
Reputation: 41301
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
.
Upvotes: 5
Reputation: 279245
The bit-pattern that means 1065353216
as an integer (3f800000
in hex) happens in your implementation to mean 1
as a float. It's not guaranteed that this will be the case in all C++ implementations, although it is common since that's the bit-pattern representing 1
as a 32-bit IEEE 754 float.
Be aware also that your code violates strict aliasing, and therefore has undefined behaviour regardless of the bit patterns.
Upvotes: 1
Reputation: 1090
So I expect to see the
0x3f800000
in output, but It prints1
instead. Why?
Because 0x3f800000
has the bit pattern 00111111100000000000000000000000
that if read according to the IEEE 754 standard is representing the float 1.0
Upvotes: 2
Reputation:
The conversion from int to float is wrong. You must do it like this:
unsigned int i=0x3f800000;
float f=(float)i;
cout<<f;
Upvotes: 1