PIC Microcontoller Radix Math Method

Binary to ASCII, 8 bit to 3 digits

from Daniel Serpell

; ========================================================
bin2ascii
; Input:  reg. W
; Output: d2 / d1 / d0 (assumed in the same bank)
; Assumed "banksel d0"
; Used 40 instructions / 30-39 cycles (counting CALL/RETURN)
; average 34.77 cycles (from 0..255).

clrf d2
clrf d1

; Test if W is more than 199 (200 to 255)
addlw .256 - .200
btfss STATUS,C
goto  digit100
bsf   d2,1
; Here we are in the 200 - 255 range, so it is possible to
; skip the .100 and .80 parts
addlw .256 - .80
goto  digit40

; Now, we have a number from -200 to -1 (0..199),
; we add 100 to detect -100 to -1 (100..199).
digit100
addlw .100
btfss STATUS,C
goto  $+3
bsf   d2,0
addlw .256 - .100

; Now, we have a number from -100 to -1 (0..99),
; we add 20 to detect -20 to -1 (80..99).
addlw .20
btfss STATUS,C
goto  digit40
bsf   d1,3
; We skip the 4 and 2, as the largest value is 8 + 1 = 9.
addlw .256 - .20
goto digit10

; Now, we have a number from -80 to -1 (0..79),
; we add 40 to detect -40 to -1 (40..79).
digit40
addlw .40
btfss STATUS,C
goto  $+3
bsf   d1,2
addlw .256 - .40

; Now, we have a number from -40 to -1 (0..39),
; we add 20 to detect -20 to -1 (20..39).
addlw .20
btfss STATUS,C
goto  $+3
bsf   d1,1
addlw .256 - .20

; Now, we have a number from -20 to -1 (0..19),
; we add 10 to detect -10 to -1 (10..19).
digit10
addlw .10
btfss STATUS,C
goto  $+3
bsf   d1,0
addlw .256 - .10

; Now, we have a number from -10 to -1 (0..9),
; we add 58 to bring it from 48 to 57 (0..9).
addlw .58
movwf d0

movlw 0x30
xorwf d1,f
xorwf d2,f

return



Archive: