Hi, I am implementing an I2C sensor and need to convert from Long to Float. In the arduino library that I'm using as a guide they use the function:
P_max = *reinterpret_cast<float*>(&scaling34)</float*>
*reinterpret_cast is not a simple conversion from Long to Float, but as far as I understand, it 'copies' the binary representation of the Long to a Float.
In my example I have a Long 'scaling34' = 1120403456 (&b01000010110010000000000000000000)
With the same binary representation for a Float I get P_max = 100.0 in a IEEE-754 converter: https://www.h-schmidt.net/FloatConverter/IEEE754.html
How do I do that conversion in CRBasic?
With the help from this forum thread how-to-convert-hex-to-ieee-754-32-bit-float-in-c I managed to come up with this function. Pi in Hex (&H40490FDB) gives me 3.141593 so it seams to work for now.
Please let me know if there is a better way to do it.
Function NumberToFloat(number As Long) As Float
Dim i As Long
Dim signbit As Long
Dim exponent As Long
Dim mantissa As Long
Dim power As Long
Dim total As Float
Dim calc As Long
Dim value As Float
signbit = (number >> 31) AND &H01
exponent = ((number AND &H7f800000) >> 23)
mantissa = (number AND &H007FFFFF)
power = -1
total = 0.0
For i = 1 To (23) Step 1
calc = (mantissa >> (23-i)) AND &H01;
total += calc * PWR(2.0, power);
power -= 1;
Next
value = PWR(-1, signbit) * PWR(2.0, exponent - 127) * (total + 1.0);
Return value;
EndFunction
Public InValue As Long
Public Result As Float
'Main Program
BeginProg
Scan (1,Sec,0,0)
InValue = &H40490FDB 'Pi in Hex (&H40490FDB) or 100.0 in dec (1120403456)
Result = NumberToFloat(InValue)
NextScan
EndProg
MoveBytes() is the instruction you need.
Thanks! That did the trick.
Public InValue As Long
Public Result As Float
'Main Program
BeginProg
Scan (1,Sec,0,0)
InValue = &H40490FDB 'Pi in Hex (&H40490FDB) or 100.0 in dec (1120403456)
MoveBytes (Result,0,InValue,0,4) ' The MoveBytes instruction is used to move binary bytes of data into a different memory location.
NextScan
EndProg