Multiplying arbitrary numbers?

This is an archive of a topic from NESdev BBS, taken in mid-October 2019 before a server upgrade.
View original topic
Multiplying arbitrary numbers?
by on (#157570)
So, I'm restructuring a method here of how I'm doing something, and I'm realizing that the simplest way to achieve this would be a simple multiplication...but I know that's not such a simple thing if not by a power of two in ASM. What's the best method you guys have for multiplying arbitrary, variable numbers?

**edit** Also - in this case, these numbers will generally be small...all products would be under 64 in value.

Thanks!
Re: Multiplying arbitrary numbers?
by on (#157571)
The obvious way is to loop through adds.

5*3 looks like:
Code:
lda #$05
sta temp

ldy #$03

jsr mult
;the rest of the code
mult:
lda #$00
clc
loop:
adc temp
dey
bne loop

If you're working with sufficiently large numbers, it may be worth putting a check in the beginning to make the smaller the looping number. 9*7 = 7*9, and doing 7 loops is better than doing 9. The above doesn't have any special case for zero, but that's easy enough to figure out if you need that. Obviously this also doesn't work if the number will exceed 255. In that case you need some 16bit math, but the process is the same.

For more advanced (and generally faster) ways, check out the posts starting on the beginning of this page: http://atariage.com/forums/topic/71120- ... cks/page-2
Or this page: http://codebase64.org/doku.php?id=base:6502_6510_maths

Edit: Yes, it should have read bne loop. Fixed now.
Re: Multiplying arbitrary numbers?
by on (#157573)
Awesome, yeah for this purpose it will do just fine. Won't need a zero case, and won't need a number larger than 64. This is quick and clean - thanks! :-)

** And btw - shouldn't that read BNE loop rather than BEQ loop? Keep adding the one number and decreasing the other until the other is zero, then jump out of the mult routine?
Re: Multiplying arbitrary numbers?
by on (#157575)
Code:
shouldn't that read BNE loop


Yes.

I like a 'look up table' for multiplication/division. It's faster.
Re: Multiplying arbitrary numbers?
by on (#157577)
dougeff wrote:
I like a 'look up table' for multiplication/division. It's faster.


Yeah, especially here, when you know your products will be so small.

If you want to actually do the calculation, at least do binary multiplication (like the one Kasumi linked to here) instead of repeated additions.
Re: Multiplying arbitrary numbers?
by on (#157617)
There's an 8x8 binary multiplication in the source code of Thwaite too.