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
You don't want to
reinterpret_cast
&bytes
, butbytes
. The former is the address of a pointer, the latter is the value (what's pointed to), which is where yourdouble
is.Also, cast to
unsigned char*
, notunsigned char* const
, so you don't cast away c-v qualifiersOutput:
Live Demo