News:

Let's find out together what makes a PIC Tick!

Main Menu

2's complement to float

Started by RGV250, May 02, 2025, 08:29 PM

Previous topic - Next topic

RGV250

Hi,
I have just found an issue with my code, one of the word values is 2's complement but I need a float.
Is is as simple as checking bit 15 for 0 and if so all is good, just move the word to float. If it = 1 then add 1, move it into the float and set bit 63?
or another thought is to use a SWORD as an intermediate step and then move that to the float.

Regards,
Bob

flosigud

Yes, if the word is signed you can just move the value to float.

top204

#2
I don't know the full code requirements of your project. However, you can temporarily cast a variable as signed or unsigned:

Dim MyWord As Word
Dim MyFloat As Float

If MyWord.SWord < 0 Then do something

Or

MyFloat = MyWord.SWord

Remember, a floating point variable is always signed, so if the sign of an inetegr variable is required to be recognised by the floating point variable, it must be designated as a signed type before being converted to a floating point format.

RGV250

Hi,
Thanks for the answers, I have done this now which so far seems to work, going to do a bit more testing / tidying up before posting the code.
The INA260 seems to be way better than the INA219.

' Read in the Current Register value.
Proc INA260_Read_Current(), Float
    Dim TempI As Float
        I2CIn SDA, SCL, INA260_I2C_Address,INA260_REG_CURRENT,[TempI]
        Result = TempI * 0.00125   'Convert to amps
EndProc

Regards,
Bob