reinterpret_cast - double to char[] to double not working - C++

2.4k views Asked by At

I am trying to send some double's in a datagram via udpSendSocket. The data is coming from a QT GUI and being sent to a VS2013 driver program (both in C++). I am using a QDataStream to put data into a QByteArray which is then sent off. Everything works fine for integers but I cannot make it work for doubles.

I have already confirmed that my transmission code works such that whatever is in datagram is being received by the driver program so I am doing all of my testing in the QT program.

At first I sent a double straight into QDataStream which claims to use IEEE 754 and then used *reinterpret_cast to convert it back to a double.

// QT Program
QByteArray datagram;
QDataStream out(&datagram, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_1);
out.setFloatingPointPrecision(QDataStream::SinglePrecision);

double test = 0.3;
out << test;
double recv = *reinterpret_cast<double*>(&datagram);

With that recv = 2.32e-317.

After that didn't work I focused on trying to convert a double to byte array back to double. Multiple sources led me to believe this would work but it is not.

double test = 0.3;
unsigned char const* bytes = reinterpret_cast<unsigned char const*>(&test);
double recv = *reinterpret_cast<double*>(&bytes);

With that recv = 1.33e-317.

sizeof(double) returns 8.

What am I doing wrong with reinterpret_cast? Should I be making this conversion a different way? Any suggestions?

Thanks

3

There are 3 answers

0
AndyG On BEST ANSWER

You don't want to reinterpret_cast &bytes, but bytes. The former is the address of a pointer, the latter is the value (what's pointed to), which is where your double is.

Also, cast to unsigned char*, not unsigned char* const, so you don't cast away c-v qualifiers

double test = 0.3;
unsigned char* bytes = reinterpret_cast<unsigned char*>(&test);
double recv = *reinterpret_cast<double*>(bytes);
std::cout << recv << std::endl;

Output:

0.3

Live Demo

0
Alexander Balabin On

In your interpret_cast example you're taking pointer to bytes which is already a pointer to the data bytes and casting to pointer to double. If you cast bytes instead and also cast to a const double* (because reinterpret_cast does not cast away constness) it will work:

double recv = *reinterpret_cast<const double*>(bytes);
0
Angew is no longer proud of SO On

@AndyG is correct about the bytes part. As for datagram: &datagram gives you the address of the QByteArray object, not the address of its contents. For that, you need data():

QByteArray datagram;
QDataStream out(&datagram, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_1);
out.setFloatingPointPrecision(QDataStream::SinglePrecision);

double test = 0.3;
out << test;
double recv = *reinterpret_cast<double*>(datagram.data());