4 bytes array into float
-
wrote on 14 Mar 2017, 09:21 last edited by
Hello,
I am using qt 4.8.5.
I have an array of 4 elements of _u8 type.
I would like to convert it into float. But I end up in wrong value.
= {1, 0, 0, 0} (hex values are 01 00 00 00)qint32 value; float value2; for(i = 0; i < 4; i++) { value = (value << 8) + (data[i] & 0xff); // if MSB is bit number 1 } value2 = (float)value;
If I out the value as int, the value I get is 16777216.
If I out the value2 as float, I get 1.67772e07. But I am expecting a float value 2.35099e-38(https://gregstoll.dyndns.org/~gregstoll/floattohex/).
How can I convert the 4 byte array into float? -
Hello,
I am using qt 4.8.5.
I have an array of 4 elements of _u8 type.
I would like to convert it into float. But I end up in wrong value.
= {1, 0, 0, 0} (hex values are 01 00 00 00)qint32 value; float value2; for(i = 0; i < 4; i++) { value = (value << 8) + (data[i] & 0xff); // if MSB is bit number 1 } value2 = (float)value;
If I out the value as int, the value I get is 16777216.
If I out the value2 as float, I get 1.67772e07. But I am expecting a float value 2.35099e-38(https://gregstoll.dyndns.org/~gregstoll/floattohex/).
How can I convert the 4 byte array into float?@sandycoolxyz Shouldn't it be like:
qint32 value = 0; for(i = 0; i < 4; i++) { value |= data[i]<<(8*i); // or (depending on byte order in the array value |= data[i]<<((4-i)*8); }
-
wrote on 14 Mar 2017, 10:11 last edited by
One option, assuming your array is always big-endian, and your code has to support both big an little-endian platforms:
quint8 a[] = {1, 0, 0, 0}; quint32 localEndian = qFromBigEndian<quint32>(a); qDebug() << *reinterpret_cast<float *>(&localEndian);
Output:
2.35099e-38
Cheers.
-
wrote on 14 Mar 2017, 10:45 last edited by
Thanks Paul Colby and jsulm for the reply.
@jsulm I believe Its the same code as mine, just using addition instead of OR.@Paul-Colby Thanks for the solution.
Cheers.
-
Thanks Paul Colby and jsulm for the reply.
@jsulm I believe Its the same code as mine, just using addition instead of OR.@Paul-Colby Thanks for the solution.
Cheers.
wrote on 14 Mar 2017, 12:44 last edited byProblems like that are exactly why people like to avoid bitwise operation when possible... For example, in this case many would prefer using an union of float & array for the conversion as it is more readable and maintainable years later...
-
Problems like that are exactly why people like to avoid bitwise operation when possible... For example, in this case many would prefer using an union of float & array for the conversion as it is more readable and maintainable years later...
@mvuori But the union would not solve the problem with endianness.
1/6