0

So I'm trying to multiply by using add and shift. I want to store the multiplicand in the accumulator and the multiplicand in the X-register. I genuinely don't know why my code isn't working but I suspect its because of the multiplicand being in the accumulator and putting the product in a separate register.

Here is my code so far:

      LDA #49
      LDX #8
      LDY #$8
      STA $700
      STX $704
loop:           ; if 1
      BCC  loop2    ; if 0, go to loop2
      CLC       ; clear carry for adc
      ADC $700      ; adc
loop2: ;     if 0
      ROL $700      ; left shift
      CLC
      ROR $704
      DEY
      BNE loop      ; if not 0, go to loop
      STA $700      ; store A in product register

Thank you for your help

  • 1
    See https://wiki.nesdev.com/w/index.php/8-bit_Multiply for examples of 8x8-bit multiplication on the 6502. – Michael May 09 '21 at 07:44

1 Answers1

2

This is the corrected version. Check double semicolon for the changes. Biggest mistake was to forget resetting accumulator and carry flag before the first loop.

      LDA #49
      LDX #8
      LDY #9    ;; you need to increase your loop by 1
      STA $700
      STX $704
      LDA #$00  ;; you need to reset acc
      CLC       ;; and clear carry
loop:           ; if 1
      BCC  loop2    ; if 0, go to loop2
      CLC       ; clear carry for adc
      ADC $700      ; adc
loop2: ;     if 0

      ;ROL $700     ;; these three lines
      ;CLC          ;; are replaced with
      ;ROR $704     ;; the two lines below

      ROR        ;; this is
      ROR $704   ;; faster

      DEY
      BNE loop      ; if not 0, go to loop
      STA $700      ; store A in product register
Emir Akaydın
  • 5,708
  • 1
  • 29
  • 57
  • Thank you very much! Why do we need to CLC before the loop and how come my initial three lines don't work? Thank you again. – Ron Borenstein May 10 '21 at 08:53
  • 1
    The very first instruction after `loop:` is a `BCC`; if you don't precede the loop with a `CLC` then the carry flag will initially be in an unspecified state. – Tommy May 11 '21 at 13:35