Programming:Display a byte as a 3-digit decimal number

From CPCWiki - THE Amstrad CPC encyclopedia!
Jump to: navigation, search

From the The Unofficial Amstrad WWW Resource:

This routine uses Firmware

;; A useful function to display a byte as a 3-digit decimal number

.txt_output equ &bb5a

;; Enter:       
;; A = 8-bit value
;; Exit:        
;; AF,BC corrupt. All other registers preserved
;; NOTE: A) The display routine works by the following procedure:
;;       1) The 8-bit value is divided by 100 then 10 and finally 1 to obtain 
;;          each digit value. Therefore 983 would produce 9,8 and 3 as each
;;          digit.
;;       2) The digit is converted into ASCII form, and displayed.
;;       3) The remainder of the division, is used for the next division.
;;          i.e. 983 divided by 100, leaves 83 as the remainder. This is
;;               divided by 10, to give 3 as the remainder.
;;       B) In the routine,
;;          B = divisor (100,10,1)
;;          C = digit value
;;          A = dividend (8-bit value)

ld b,100                   ;divisor to obtain 100's digit value
call print_decimal_digit   ;display digit
ld b,10                    ;divisor to obtain 10's digit value
call print_decimal_digit   ;display digit
ld b,1                     ;divisor to obtain 1's digit value

;; B = divisor
;; A = dividend


;; simple division routine
ld c,0                     ;zeroise result 

sub b                      ;subtract divisor
jr c,display_decimal_digit ;if dividend is less than divisor, the division
                           ;has finished.

inc c                      ;increment digit value
jr decimal_divide

add a,b                   ;add divisor because dividend was negative,
                          ;leaving remainder.

;; A = dividend
;; C = result of division

;; digit is a number between 0..9
;; convert this into a ASCII character '0'..'9' then display this

push af
ld a,c                    ;get digit value
add a,"0"                 ;convert value into ASCII character
call txt_output           ;display digit
pop af