Our full technical support staff does not monitor this forum. If you need assistance from a member of our staff, please submit your question from the Ask a Question page.


Log in or register to post/reply in the forum.

Convert Long to Float


--dd-- Sep 22, 2022 03:27 PM

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?


--dd-- Sep 26, 2022 10:53 AM

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

 


JDavis Sep 28, 2022 05:29 PM

MoveBytes() is the instruction you need.


--dd-- Sep 29, 2022 07:36 AM

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

Log in or register to post/reply in the forum.