Skip to content

Commit

Permalink
Forth: Add DEC. (Print unsigned decimal number)
Browse files Browse the repository at this point in the history
  • Loading branch information
adumont committed Feb 5, 2022
1 parent bcd2a62 commit f354777
Showing 1 changed file with 65 additions and 7 deletions.
72 changes: 65 additions & 7 deletions forth.s
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,9 @@ RES_vec:
; clear the OK flag
stz OK

; clear the PRT0 flag (print leading 0)
stz PRT0

; This is a Direct Threaded Code based FORTH

; Load the entry point of our main FORTH
Expand Down Expand Up @@ -374,6 +377,27 @@ noheader "FETCH_OK"
stz 1,x
JMP DEX2_NEXT

defword "DECPRINT","DEC.",
; ( n -- )
; Print the number in decimal form
LDA 2,x
STA BIN+0
LDA 3,x
STA BIN+1
JSR hex16toBCD
LDY #5
STY PRT0 ; 6 digits, so 6-1=5 where we don't want to print leading 0
LDA BCD+2
JSR print_byte
LDA BCD+1
JSR print_byte
LDA BCD+0
JSR print_byte
STZ PRT0 ; reset the PRT0 flag
LDA #' '
JSR putc
JMP do_DROP

defword "COLON",,
; push IP to Return Stack
LDA IP+1 ; HI
Expand Down Expand Up @@ -2668,21 +2692,25 @@ print_byte:
LSR ; to get HI nibble
LSR
LSR
JSR nibble_value_to_asc
JSR putc

JSR print_nibble
PLA
AND #$0F ; LO nibble
JSR nibble_value_to_asc
JSR putc
JSR print_nibble
RTS

nibble_value_to_asc:
print_nibble:
BNE :+
; digit is a 0
DEC PRT0
BPL :++ ; PRT0>0 --> we don't print it
: STZ PRT0 ; digit wasn't 0, so we clear PRT0 flag
CMP #$0A
BCC @skip
ADC #$66
@skip:
EOR #$30
JSR putc
:
RTS

nibble_asc_to_value:
Expand Down Expand Up @@ -2710,6 +2738,32 @@ nibble_asc_to_value:
CLC
RTS

hex16toBCD:
; http://www.6502.org/source/integers/hex2dec-more.htm
; expect a 16-bit HEX number in BIN+{0,1}
; returns a 24-bit BCD number in BCD+{0,1,2}
SED ; Switch to decimal mode
STZ BCD+0 ; we erase the result area
STZ BCD+1
STZ BCD+2
LDY #16 ; The number of source bits
@cnvbit:
ASL BIN+0 ; Shift out one bit
ROL BIN+1
LDA BCD+0 ; And add into result
ADC BCD+0
STA BCD+0
LDA BCD+1 ; propagating any carry
ADC BCD+1
STA BCD+1
LDA BCD+2 ; ... thru whole result
ADC BCD+2
STA BCD+2
DEY ; And repeat for next bit
BNE @cnvbit
CLD ; Back to binary
RTS

; Interrupts routines

IRQ_vec:
Expand Down Expand Up @@ -2868,7 +2922,11 @@ INP_LEN: .res 1 ; Length of the text in the input buffer
INPUT: .res 128 ; CMD string (extend as needed, up to 256!)
INP_IDX: .res 1 ; Index into the INPUT Buffer (for reading it with KEY)
OK: .res 1 ; 1 -> show OK prompt
PRT0: .res 1 ; flag we use to know if we print leading zeros. <0 we print the 0, otherwise we don't
SCRATCH: .res 8 ; 8 bytes we can use in routines...

BIN = SCRATCH
BCD = SCRATCH+2

; Base of user memory area.
USER_BASE:

0 comments on commit f354777

Please sign in to comment.