Search code examples
assemblybinaryavrmultiplicationshift

Multiplication in avr assembly


I can't understand the way that binary multiplication takes place in avr code. Here is code from avr freaks. What exactly does "ror" and "lsr" do? I thought that for multiplication in binary we need lsl instead.

.def    mc8s    =r16        ;multiplicand
.def    mp8s    =r17        ;multiplier
.def    m8sL    =r17        ;result Low byte
.def    m8sH    =r18        ;result High byte
.def    mcnt8s  =r19        ;loop counter


 mpy8s: sub m8sH,m8sH   ;clear result High byte and carry


    ldi mcnt8s,8    ;init loop counter
    m8s_1:  brcc    m8s_2       ;if carry (previous bit) set


    add m8sH,mc8s   ;    add multiplicand to result High byte
   m8s_2:   sbrc    mp8s,0      ;if current bit set

    sub m8sH,mc8s   ;    subtract multiplicand from result High
    asr m8sH        ;shift right result High byte

    ror m8sL        ;shift right result L byte and multiplier
    enter code here

    dec mcnt8s      ;decrement loop counter
   enter code here


    brne    m8s_1       ;if not done, loop more
    ret

Solution

  • As you know, multiplication can be performed using shifting and addition, e.g.

       101
       101
       ===
       101
    1 01
    = ====
    1 1001
    

    Notice that although the numbers fit in 4 bits, I needed to use more bits for the addition. To avoid this, the code you quote shifts the result rather than the number to be added.

      101
      --- -
       10 1
       -- --
        1 01
      101
      ===
      110 01
      --- --
       11 001
       -- ----
        1 0001
    

    This way only 4 bits of addition are needed.