; Oct. 26th. 1992, A. Bocher, danelec electronics, Denmark
;
; Routine to convert a 16 bit binary number into 5-digit BCD or ASCII code.
; This is a smaller version of the HTOD subroutine in the M68HC11
; reference manual. Size: 21-35 bytes vs. 57 bytes for HTOD.
;
; Entry: X-register points to the 16-bit binary number to be converted.
; Exit:  bcdbuf is the address of a 5-byte buffer, each byte containing a
;        BCD-digit in the lower nibble.
;        All registers are intact on exit.
;
;bcdbuf:  | 0 0 0 0 D C B A |     (MSD) BCD output buffer
;         | 0 0 0 0 D C B A |
;           | | | | | | | |
;         | 0 0 0 0 D C B A |
;         | 0 0 0 0 D C B A |     (LSD)

RAM       equ       $0000
ROM       equ       $E000

noofdigs  equ       5                   ;Number of BCD-digits
base      equ       10                  ;Base to be converted to

          org       RAM
bcdbuf    rmb       noofdigs

          org       ROM
bin2bcd   pshy                          ;* Save registers (optional)
          pshx                          ;*          - " -
          pshb                          ;*          - " -
          psha                          ;*          - " -
          ldy       #noofdigs-1         ;Loopcounter & pointer into bcdbuf
          ldd       ,x                  ;Get 16-bit binary value
loop      ldx       #base               ;Divide by "base"
          idiv
          addb      #$30                ;* convert to ASCII (optional)
          stab      bcdbuf,y            ;Save remainder in "bcdbuf"
          xgdx                          ;and use integer result as input for
          dey                           ;the next calculation
          bne       loop                ;2nd.last digit? if no, loop back
          addb      #$30                ;* convert MSD to ASCII (optional)
          stab      bcdbuf              ;and store MSD
          pula                          ;* Restore registers (optional)
          pulb                          ;*            - " -
          pulx                          ;*            - " -
          puly                          ;*            - " -
          rts
          end

; Theory (shown in decimal for clarity):
; 56789d is to be converted to BCD.
; 56789 div 10 = 5678, remainder = 9. Save remainder.
; 5678 div 10 = 567, remainder = 8. Save remainder.
; 567 div 10 = 56, remainder = 7. Save remainder.
; 56 div 10 = 5, remainder = 6. Save remainder and quotient.
; That's it.
