Shop OBEX P1 Docs P2 Docs Learn Events
Fixed Point to Floating Point — Parallax Forums

Fixed Point to Floating Point

RogerInHawaiiRogerInHawaii Posts: 87
edited 2009-08-18 00:32 in Propeller 1
I have a fixed point variable in my Spin code. It has 16 bits of integer value and 16 bits of fractional value. It's coming from an external device in Fixed Point format so I have no direct control over its format. I want to be able to use that in some floating point operations, such as FloatMath.FMul(MyFixedPointVal, MyFLoatingPointVal).

But that clearly doesn't work since the FMul expects both arguments to already be floating point values.

How can I convert my Fixed Point variable into the Floating Point format?

Comments

  • TimmooreTimmoore Posts: 1,031
    edited 2009-08-17 23:21
    Receive it as 2 integers (separated by .). Convert both to float, then divide fractional part by 2**16 and then add integer prt.
  • John AbshierJohn Abshier Posts: 1,116
    edited 2009-08-17 23:31
    I think we need more info on the format. Are numbers positive only? This may work; it is off the top of my head and not tested.
    MyFloatInt := F.FFloat(MFP >> 16) MyFloat is the integer portion of the value. Or
    MyFloatInt := F.FFloat(MFP ~> 16) if the first bit is a sign
    temp := MFP & $FFFF get the lower 16 bits
    MyFloatFrac := F.FDiv(F.FFloat(temp), F.FFloat(65536)) could be 65535
    MyFloat := F.FAdd(MyFloatInt, MyFloatFrac)

    John Abshier
  • RogerInHawaiiRogerInHawaii Posts: 87
    edited 2009-08-17 23:35
    Yes, the values are always positive.

    Those approaches, using FFloat to convert and then combine, looks good!

    I'll give it a try.

    Thanks
  • mparkmpark Posts: 1,305
    edited 2009-08-17 23:47
    John Abshier said...
    I think we need more info on the format. Are numbers positive only? This may work; it is off the top of my head and not tested.
    MyFloatInt := F.FFloat(MFP >> 16) MyFloat is the integer portion of the value. Or
    MyFloatInt := F.FFloat(MFP ~> 16) if the first bit is a sign
    temp := MFP & $FFFF get the lower 16 bits
    MyFloatFrac := F.FDiv(F.FFloat(temp), F.FFloat(65536)) could be 65535
    MyFloat := F.FAdd(MyFloatInt, MyFloatFrac)

    John Abshier
    Wouldn't it work just as well simply to divide MFP by 65536? I.e., F.FDiv( F.FFloat(MFP), 65536.0 )
  • Jay KickliterJay Kickliter Posts: 446
    edited 2009-08-18 00:32
    If you can, the best thing would be to keep it in fixed point. You'd save a lot of resources by not having to go FP. But, if you're already using FP, then mpark's solution is the way to go.

    Jay
Sign In or Register to comment.