Shop OBEX P1 Docs P2 Docs Learn Events
IF...THEN Syntax — Parallax Forums

IF...THEN Syntax

aaron87aaron87 Posts: 6
edited 2007-10-04 11:05 in BASIC Stamp
I·notice that for IF ... THEN Syntax, all comparisons are performed using unsigned, 16-bit math. This can lead to strange results if you mix signed and unsigned numbers in IF...THEN conditions. Does anyone know how to tackle this problem, cos i need to include signed number in the IF ... THEN Syntax? thanks.

Comments

  • Mike GreenMike Green Posts: 23,101
    edited 2007-09-30 16:33
    You just have to be careful about the numbers you are comparing. You can sometimes sort this out by checking the numbers you want to compare for whether they're less than zero or greater or equal to zero and use different IF statements if both values are less than zero or both are greater than zero. If one value is less than zero and the other is greater or equal to zero, you already have your answer. It's not convenient, but it works.
  • allanlane5allanlane5 Posts: 3,815
    edited 2007-10-01 00:02
    In signed arithmetic, a 'negative' number has the high-bit set. You can use that in IF-THEN statements.
  • Tracy AllenTracy Allen Posts: 6,664
    edited 2007-10-01 00:59
    Sometimes you can make comparisons by adding a constant. For example, if you want to compare temperatures that can range from -273 to +1000, Celsius, then convert it to Kelvin or add any arbitrary constant that will make all the expected values positive.
    Temp1 CON -25 + 273
    Temp2 CON +25 + 273

    IF Celsius+273 > Temp1 AND Celsius+273< Temp2 THEN ...

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Tracy Allen
    www.emesystems.com
  • TechnoRobboTechnoRobbo Posts: 323
    edited 2007-10-04 11:05
    allanlane5 said...
    In signed arithmetic, a 'negative' number has the high-bit set. You can use that in IF-THEN statements.
    ' {$STAMP BS2}
    ' {$PBASIC 2.5}
    x VAR Word
    y VAR Word
    x=0
    y=0
    DO
    · DEBUG CR,CR,"input value x: "
    · DEBUGIN SDEC x
    · DEBUG CR,"input value y: "
    · DEBUGIN SDEC y

    · IF (x-y)=>$8000 THEN···· 'check high bit - processors compare by subtracting
    ··· DEBUG CR,"y is greater than x"
    · ELSEIF y=x THEN
    ··· DEBUG CR, "y=x"
    · ELSE
    ··· DEBUG CR,"x is greater than y"
    · ENDIF
    LOOP

    You have to include error checking to insure your highest magnitude is an absolute value of 32767. Otherwise you have anarchy or, at least, a really confused processor.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Have Fun


    TR

    Post Edited (TechnoRobbo) : 10/4/2007 6:21:59 PM GMT
Sign In or Register to comment.