View Full Version : Two's compliment

12-04-2006, 11:15 AM
This is currently MBasic, but i would like to get it working on the basic stamp2 as well

I am trying to get an accurate count from two bytes, one high and one low. I can get the low byte to work but the high byte doesn’t seem to want to work. When I have just the low byte part of my code then it counts fine it counts up and down smoothly. As soon as I put in the high byte part in it will only count one way correctly. Clock wise it counts up by one and other direction just makes it add 15 each time. What am i doing wrong?

__________________________________________________ _______________

Total var sword
Work var sword 'small
small var sword
Large var sword
Work2 var sword 'large

Work2 = 0
Work = 0
Total = 0
Small = 0
OE con P10
SEL con P11

High SEL
Low OE
High OE
Dirl = $FF


low OE

work2 = INL
Large = Large + Work2
If Work2 > 127 then
Large = Large - 256

High SEL
Work = INL
small = small + work
if Work > 127 then
small = small - 256
High OE

Total = Total + small + Large

serout S_out,I38400,["Total = ",sDec Total," High = ",bin Large," Low = ",bin small,13]

Large = 0
Small = 0

Goto main

12-05-2006, 11:43 AM
You have made an incorrect assumption.ˇ MBASIC doesn't use two's complement when dealing with swords (signed words). It's not a one's complement either.ˇIt uses sign and magnitude.

a two'scomplement word has a range ofˇˇ-32,768 to 32,767 ($8000 to $7FFF respectively)
an MBASIC sword has a range of -32,767 to 32,767 ($FFFF to $7FFF respectively) and $8000 rolls into 32,768.

The most significant bit is actually a sign bit.ˇYour thinking $FFFF is -1 but it's actually -32,767. Yikes!

Gotta rethink that code.

Have Fun