Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast double to float pointer?

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

like image 271
Zack Lee Avatar asked Nov 10 '17 08:11

Zack Lee


1 Answers

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;
like image 89
DevSolar Avatar answered Sep 30 '22 15:09

DevSolar