Shop OBEX P1 Docs P2 Docs Learn Events
Help with Boolean Logic — Parallax Forums

Help with Boolean Logic

soccerboysoccerboy Posts: 2
edited 2005-05-27 17:45 in BASIC Stamp
How can I get a BS2 to recognize negative values while using boolean logic. Here is an example:

X VAR Word

X = -2

If (X > 2) THEN DEBUG "Hello"

This code in my BS2 will still return Hello.

Thanks

Comments

  • Paul BakerPaul Baker Posts: 6,351
    edited 2005-05-26 12:34
    A negative number in binary is expressed as twos compliment which is calculated by taking the NOT of the positive value then adding 1, so for -2 the inverse of 2 is $FFFD, add 1 and you get $FFFE, if you then use an unsigned operator on the two numbers youll get goofy results ($FFFE > $0002 or -2 > 2).
  • Jon WilliamsJon Williams Posts: 6,491
    edited 2005-05-26 12:42
    As Paul pointed out, negative numbers are stored in two's compliment form which is giving you trouble.· One way to detect a negative number is to look at bit15 of the value (it will be set when negative).· You could update your logic like this:

    · IF (x.BIT15 = 0) AND (x > 2) THEN
    ··· DEBUG "Hello"
    · ENDIF

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Jon Williams
    Applications Engineer, Parallax
  • clayljclaylj Posts: 9
    edited 2005-05-26 14:21
    Paul and Jon are correct about the twos compliment issue and the fact that a bit set in position 15 makes the number a negative. Having said that. the simple answer is this:

    X VAR Word
    
    X = -2
    
    IF (X < $FFFE) THEN DEBUG "Hello"
    



    You do the twos compliment by converting the decimal number to binary then logically NOT each bit and add 1.

    2 = 0000000000000010
    NOT 2 = 1111111111111101
    add 1 = 1111111111111110

    Converting this to Hex, 1111 1111 1111 1110, you get $FFFE.

    Larry
  • Tracy AllenTracy Allen Posts: 6,658
    edited 2005-05-26 14:44
    If you want the IF statement to work with any twos-complement value of X from -32768 to +32767, then use an offset as follows
    X = -2
    Y = 2
    If (X+32768 > Y+32768) THEN DEBUG "Hello"

    Plug in a few numbers for X and Y to get a feel for how it works. The Stamp happily works with + numbers.

    soccerboy said...
    How can I get a BS2 to recognize negative values while using boolean logic. Here is an example:

    X VAR Word

    X = -2

    If (X > 2) THEN DEBUG "Hello"

    This code in my BS2 will still return Hello.

    Thanks
    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Tracy Allen
    www.emesystems.com
  • soccerboysoccerboy Posts: 2
    edited 2005-05-26 18:51
    Thanks all for your advice. I will try out all the suggestions and see which one is best suited for my code. I think John Williams suggestion is the best for my situation.
  • Ryan ClarkeRyan Clarke Posts: 738
    edited 2005-05-27 17:45
    Won't John's take longer (the compound statement) compared to a straight comparison? (just curious)

    Ryan
Sign In or Register to comment.