; by FredMaher Madrid 10 Nov 02, Rewritten for SX by James Newton Feb 03.
; Using an extension of the >4 add 3 algorithm

	device  sx18
;	device  pic16c54,xt_osc,wdt_off,protect_off
	reset   start:

BCDdigits = 5
BINdigits = 3

       org 16
bcd 	DS	BCDdigits
bin 	DS	BINdigits

IFNDEF count
count           DS	1
	ENDIF
IFNDEF temp
temp            DS	1
	ENDIF

;
	org 	0
Start:
;-----------------------------------------------------------------
;Hex(Binary) to BCD routine
;-----------------------------------------------------------------
Main:
	mov	temp, #BCDdigits
	mov	w, #bcd
	mov	fsr, w
BCDclear:
	clr	indf
	inc	fsr
	djnz	temp, BCDclear:
	
Testvals:
	mov	W, #0FFh
	mov	bin, W
	mov	W, #0FFh
	mov	bin+1, W
	mov	W, #0Fh
	mov	bin+2, W

	call	bin2bcd:
	
Convend:  ; remove when in main prg
	jmp	Convend:	; remove when in main prg

;-----------------------------------------------------------
; End main Bin Bcd
;------------------------------------------------------------

bin2bcd:
	mov	count, #BINdigits * 8	; count max value
	
Shifting:
	test	count
	snb	Z
	ret	; bin number is now converted 2 bcd
	dec	count
	
;----------------------------
; Now left shift all registers

	clrb	C
	mov	temp, #BINdigits
	mov	fsr, #bin
BINrlLoop:
	rl	indf
	inc	fsr
	djnz	temp, BINrlLoop:

	mov	temp, #BCDdigits
	mov	fsr, #bcd
BCDrlLoop:
	rl	indf
	inc	fsr
	djnz	temp, BCDrlLoop:


; next step check those which are >4 and add 3

	test	count
	snb	Z	; finish without testing >4
	ret

Nibtests:	;Test BCD, high and low nibbles. If greater than 4 ( or 40) add 3 (or 30)
	mov	temp, #BCDdigits
	mov	fsr, #bcd
BCDadjLoop:
	mov	W, #0Bh ;(16-5)
	add	W, indf	;DC set if carry from bit 3 to 4
	mov	W, #03h	; >4 add3
	snb	DC
	add	indf, W

	mov	W, #0B0h	; is high nibble more than 5?
	add	W, indf
	mov	W, #30h	; add 3 to high nibble
	snb	C
	add	indf, W
	inc	fsr
	djnz	temp, BCDadjLoop:
	
	jmp	Shifting:
