PDA

View Full Version : Help with Boolean Logic

soccerboy
05-26-2005, 11:42 AM
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

Paul Baker
05-26-2005, 07:34 PM
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 Williams
05-26-2005, 07:42 PM
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

claylj
05-26-2005, 09:21 PM
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

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

Larry

Tracy Allen
05-26-2005, 09:44 PM
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 (http://www.emesystems.com)

soccerboy
05-27-2005, 01:51 AM
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 Clarke
05-28-2005, 12:45 AM
Won't John's take longer (the compound statement) compared to a straight comparison? (just curious)

Ryan