Shop OBEX P1 Docs P2 Docs Learn Events
32 bit math (input 32 bit value from keypad) what''s wrong? — Parallax Forums

32 bit math (input 32 bit value from keypad) what''s wrong?

ArchiverArchiver Posts: 46,084
edited 2003-10-01 05:13 in General Discussion
>I still seem to be having problems with the 32 bit add routine. I am not sure
>what I am doing wrong but here is an example that doesn't seem to work:
>89999999 + 1
>It seems like the carry from low word sum to high word sum is getting lost.
>Would you please provide an example of how to perform the above summation
>using debug to display the results. This is how I tried to test it:
>x0=9999
>x1=8999
>y0=1
>y1=0
>
>gosub add1616
>debug dec z1,dec z0
>
>I assume my problem must be in the way I am trying to display the sum but I
>can't seem to figure out the problem. Thanks!


I see the problem. You are working in base 10, while the algorithm
is base 2. (Actually, base 10000 and base 65536). It has to do with
what the maximum value is that you store in each word, before you get
a carry to the next word. You are rolling over from 9999 to 10000,
while my algorithm rolls over from 65535 (=%1111111111111111) to
65536 (=%10000000000000000). The representation of 89999999 is
different in these two bases:
(89999999) = 8999 * 10000 + 9999 in base 10000
so x1=8999 and x0=9999
whereas,
(89999999) = 1373 * 65536 + 19071 in base 2^16
so x1=1373 and x0=19071

It is no wonder the same algorithm does not work for both ways of
representing the number. Both ways are equally valid, and in fact,
for purpose of keypad and display, the decimal method is probably
better. Here is a base 10000 algorithm..

x1=8999 ' 0<=x1<=9999
x0=9999 ' ditto x0
y1=0 ' ditto y1
y0=1 ' ditto y0
add104: ' for addition modulo base 10000
z0 = x0+y0 ' add low words, sum can be up to 19998
z1 = x1+x2 + (z0/10000) ' add high words plus carry from low
z0 = z0//10000 ' adjust low word to remainder <10000
debug dec z1,dec4 z0,cr


With that, you add 1 to 9999, and get z0=10000. Then add 8999 + 0 +
(10000/10000) and get z1=9000. Adjust z0 modulo 10000 and get z0=0.
So the answer is (surprise) 90000000.


The binary method is better in cases when a lot of computation is
called for; especially if multiplication and division etc are
involved. However, then the computer has to work a little bit more
when it comes time to change binary back into decimal for display.

You might be interested in these pages,
http://www.silab.it/frox/stamp/bs2_math.htm
which also have BCD math routines for the Stamp, as well as a
different approach to 32 bit binary. BCD is well suited to
keypad/LCD, as each nibble rolls over at 9, with a carry into the
next higher nibble.

-- Tracy
Sign In or Register to comment.