Multiplication with PIC Assembly


I was programming a PIC microcontroller in assembly and noticed that it doesn't have a native multiply function. Being the adventurous programmer that I am, I decided to write my own. It is based on what is known as the Peasant multiplication algorithm.

Assuming X, Y, and ANS are defined bytes of memory, with X*Y ≤ 255 and ANS = 0, the following algorithm will multiply X and Y, storing the result in ANS.

MUL:        ; X * Y = ANS
            movlw   1
            subwf   X, w
            btfss   STATUS, C
            goto    END_MUL             ; while x >= 1
            btfss   X, 0                ;    if x is odd
            goto    END_MUL_IF
            movf    Y, w
            addwf   ANS, f              ;       ANS += Y
END_MUL_IF: bcf     STATUS, C           ;    clear carry
            rrf     X, f                ;    X >>= 1
            bcf     STATUS, C           ;    clear carry
            rlf     Y, f                ;    Y <<= 1
            goto    MUL