PIC Microcontoller Math Method

Multiply 4 x 4 bits

From John Payson, Ray Gardiner, Dmitry Kiryashov

See further discussion in Square

; 4x4 bit multiply
; result in W
; by  John Payson
       movlw   0
       bcf     C
       btfss   n1,0
       addwf   n2,w
       rlf     n2,f
       btfss   n1,1
       addwf   n2,w
       rlf     n2,f
       btfss   n1,2
       addwf   n2,w
       rlf     n2,f
       btfss   n1,3
       addwf   n2,w
       rlf     n2,f
       swapf   n2,f
; 15 cycles, putting the result in W and
; leaving n1 and n2 untouched at the end.
; Striking the requirement that n2 be untouched would save the
; last two cycles.
; Note that if n1<=15 and n1*n2<=255 this routine will ; produce a correct result even if n2>15;
; the value in n2 will be trashed in such a case, though.


; 4x4 bit multiply
; by  John Payson
; result in n2...
       swapf   n1,w    ; Assume top 4 bits zero
       btfss   n2,0
       addwf   n2,f
       rrf     n2,f

If we have Cy=1 before entering this code fragment and we skip first addition we'll got error.


       btfss   n2,0
       addwf   n2,f
       rrf     n2,f
       btfss   n2,0
       addwf   n2,f
       rrf     n2,f
       btfss   n2,0
       addwf   n2,f
       rrf     n2,f
; 13 cycles, leaving the result in n2.
; This one won't work if either factor is oversized.


; 4x4 bit multiply
; by Ray Gardiner
       ;  X*Y ; result left in W
       ;  X and Y are 4 bits
       ;
       ;
       CLRW            ; Clear Result
       CLRC            ; Clear Carry for RLF later                     ;
       BTFSC   Y,0     ; ?*1
       ADDWF   X,W     ; W = ?X
       RLF     X,F     ; X = 2X
                       ;
       BTFSC   Y,1     ; ?*2
       ADDWF   X,W     ; W = ?X + ?2X
       RLF     X,F     ; W = 4X

       BTFSC   Y,2     ; ?*4
       ADDWF   X,W     ; W = ?X + ?2X + ?4X
       RLF     X,F     ; W = 8X

       BTFSC   Y,3     ; ?*8
       ADDWF   X,W     ; ?X + ?2X + ?4X + ?8X
       ;;;;;;;;;;;;;;;;;;;;;;;;;

       13 cycles result in W  13 bytes of code space


Looking back, I now realise that is what John Payson has already
posted. Albeit in a different form. Sigh(!)


;       4 X 4 multiplication
; by Dmitry Kiryashov
       movfw   x       ;0000abcd
       addwf   x,F
       btfss   y,0     ;0000efgh
       movlw   0
       btfsc   y,1
       addwf   x,W
       rlf     x,F
       btfsc   y,2
       addwf   x,W
       rlf     x,F
       btfsc   y,3
       addwf   x,W     ;result in W
;       12 clocks/words

Comments: