Question about Negative numbers
qqqzhouhk
Posts: 2
in BASIC Stamp
HI, I have a question about calculation of negative numbers. Below is a easy code shows the problem that I occurred:
' {$STAMP BS2}
' {$PBASIC 2.5}
Result VAR Word
tilt VAR Word
tilt = 500
Result=(tilt-750)/3
DEBUG SDEC ? Result
DEBUG SDEC ? ABS Result
As we know, Result here should be -83.33, which is negative. But the DEBUG shoes the Result is 21762. I think it might be some problem with 2's complements, but I don't know how exactly solve it. Can anyone help me? Thanks guys!
' {$STAMP BS2}
' {$PBASIC 2.5}
Result VAR Word
tilt VAR Word
tilt = 500
Result=(tilt-750)/3
DEBUG SDEC ? Result
DEBUG SDEC ? ABS Result
As we know, Result here should be -83.33, which is negative. But the DEBUG shoes the Result is 21762. I think it might be some problem with 2's complements, but I don't know how exactly solve it. Can anyone help me? Thanks guys!
Comments
Result=(tilt/3-250)
Or, if tilt can go negative, say, a minimum of -1500:
Result=((tilt+1500)/3-750)
Multiplication is okay with twos complement, so long as the result does not overflow the -32768 to +32767 limits. So another way is to multiply instead of divide, approximately:
Resultx10=(tilt-750)*33
okay so long as tilt is in the range -242<tilt<992.