I have some trouble to get my float value out of a QVariant.
I call a function, which returns a QVariant, but when I convert it to a float value, like this:
float resf = result.toFloat();
The result is always 0.0000000. That's not the result I expect.
The QVariant itself is not empty:
It contains the data I need.
When I take the last hexadecimal values and feed them to an IEEE 754 Converter, I got the result I expected:
0x411a8ad8 = 9.658897
- Why is result not the one I expected? (Because each element in QVariant can store 2-Bytes e.g. 0x0041, so the conversion failed?)
- How do I get my float value?
Edit1: After goug's suggestion:
bool convert = false;
convert = result.canConvert<float>(); =>true
QVariant::Type type = result.type(); =>ByteArray
QString str_typename = result.typeName(); =>QByteArray
But the results are still the same:
QByteArray ba = result.toByteArray();
float fl = ba.toFloat(); =>fl = 0.00000000000
Edit2: After aatwo's suggestions:
bool bValid = true;
result.toFloat(&bValid); =>bValid = false
bValid = true;
ba.toFloat(&bValid); =>bValid = false
So, both conversions failed, even "canConvert" returns "true".
Trying:
QByteArray floatByteArray = result.toByteArray();
float floatValue = *(float*)(floatByteArray.data());
also returns not the value I expected:
But I get it working:
quint32 temp = ((char)ba[0] << 24) + ((char)ba[1] << 16) + ((char)ba[2] << 8) + (char)ba[3];
float* out = reinterpret_cast<float*>(&temp); =>out = 9.658897
Thanks!