I'm trying to cast double to float pointer but I don't know the proper way to do it.
Here's my code
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
float *f;
double d = 10;
f = reinterpret_cast<float*>(&d);
d = 20;
std::cout << "RESULT : " << *f << std::endl;
return 0;
}
And I get the following result.
RESULT : 0
Program ended with exit code: 0
How do I properly cast double to float pointer?
ADD : The result I expect to get is 20
Consider:
#include <cstdio>
#include <cassert>
using namespace std;
int main()
{
double d = 10;
float f;
assert( sizeof d == 8 );
assert( sizeof f == 4 );
unsigned char * d_ = (unsigned char *)&d;
printf( "%hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", d_[0], d_[1], d_[2], d_[3], d_[4], d_[5], d_[6], d_[7] );
}
This, at least on my machine, gives the following output:
0 0 0 0 0 0 24 40
Explanation:
That is the internal representation of a double
with value 10
.
By casting the double *
to float *
, you are only looking at the first four bytes of this -- 0 0 0 0
. Do you see why you are getting a 0
output when you dereference the pointer?
(Aside from, as others have pointed out, the dereferencing of the pointer being undefined behaviour due to breaking strict aliasing.)
Solution:
What you probably want is to cast the value of d
:
static_cast<float>(d);
You can then store that value in an object of the correct type:
float f = static_cast<float>(d);
float * fp = &f;
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