PIC Microcontroller MathMethod

BCD (packed) subtraction

From: Scott Dattalo

Translated and optimized for the Scenix SX by Nikolai Golovchenko

;******************************************
;bcd_sub
;
; Computes  x = x - y
; where x and y are all 8-bit packed BCD numbers
; Exits with C=0 if x<y, and with z=1 if x-y = 0
;
; Size: 14 instructions
; Execution time including return: 14/15 cycles

bcd_sub
	mov	W, y		;x = x - y
	sub	x, W

	clr	W
	sb	DC		;if lsn of x < lsn of y (dec)
	 or	W, #$06	;then substract extra 6
	snb	C		;Similarly for the msn
	 jmp	bcd_sub2

	or	W, #$60
	sub	x, W		;correct result
	clrb	C		;restore carry
	ret
bcd_sub2
	sub	x, W		;correct result
	setb	C		;restore carry
	ret
With result in a different register:
;******************************************
;bcd_sub_to
;
; Computes  s = x - y
; where x and y are all 8-bit packed BCD numbers
; Exits with C=0 if x<y, and with z=1 if x-y = 0
;
; Size: 15 instructions
; Execution time including return: 15/16 cycles

bcd_sub_to
	mov	W, y		;x = x - y
	mov	W, x-W
	mov	s, W

	clr	W
	sb	DC		;if lsn of x < lsn of y (dec)
	 or	W, #$06	;then substract extra 6
	snb	C		;Similarly for the msn
	 jmp	bcd_sub_to2

	or	W, #$60
	sub	s, W		;correct result
	clrb	C		;restore carry
	ret
bcd_sub_to2
	sub	s, W		;correct result
	setb	C		;restore carry
	ret