aboutsummaryrefslogtreecommitdiff
path: root/src/printnum.s
diff options
context:
space:
mode:
authorB. Watson <urchlay@slackware.uk>2026-03-29 23:36:44 -0400
committerB. Watson <urchlay@slackware.uk>2026-03-29 23:36:44 -0400
commit429938fa67beef12eb348dec04d748ab58b00678 (patch)
treedf59be6a9084f5e58675ef0333bb7ad7c3bb946b /src/printnum.s
parent4ab26eee1dd329152cd2424b0851f2ce950f96bc (diff)
downloadfujinet-chat-429938fa67beef12eb348dec04d748ab58b00678.tar.gz
Banish itoa(), save 170 bytes.
Diffstat (limited to 'src/printnum.s')
-rw-r--r--src/printnum.s80
1 files changed, 80 insertions, 0 deletions
diff --git a/src/printnum.s b/src/printnum.s
new file mode 100644
index 0000000..8b97db9
--- /dev/null
+++ b/src/printnum.s
@@ -0,0 +1,80 @@
+; print a number to the screen.
+; based on Ullrich von Bassewitz's itoa.s from the cc65 lib src.
+; it's modified to:
+; - only support base 10.
+; - only support unsigned int.
+; - print the result directly to the fnchat screen, or
+; - store the result directly in numbuf.
+
+ .importzp sreg
+ .import _scr_putc_active, _scr_current, _scr_active, _numbuf
+ .export _scr_cur_printnum, _scr_act_printnum, _num_to_numbuf
+
+ ; sreg+2 bit 7 is a flag that means "print" if set, or "store in numbuf:
+ ; if clear. also, the bottom bits of sreg+2 are the buffer position, when
+ ; bit 7 is clear.
+
+_num_to_numbuf:
+ ldy #0
+ sty sreg+2
+ beq printnum
+
+_scr_cur_printnum:
+ ldy _scr_current
+ sty _scr_active
+
+_scr_act_printnum:
+ ldy #$80
+ sty sreg+2
+
+printnum:
+ sta sreg
+ stx sreg+1
+
+ lda #0
+ pha ; sentinel
+
+divloop:
+ ldy #$10 ; 16-bit remainder
+ lda #0
+
+shift:
+ asl sreg
+ rol sreg+1
+ rol a
+ cmp #$0a ; radix
+ bcc nosub
+ sbc #$0a
+ inc sreg
+
+nosub:
+ dey
+ bne shift
+
+ ora #$30 ; make it an ASCII digit
+ pha ; save digit on stack
+
+ ; are we done yet?
+ lda sreg
+ ora sreg+1
+ bne divloop ; nope!
+
+ ; get the results from the stack and print.
+digitloop:
+ pla
+ beq done ; found sentinel? we're done.
+ ldy sreg+2
+ bpl store
+ jsr _scr_putc_active
+ jmp digitloop
+
+store:
+ sta _numbuf,y
+ iny
+ lda #0
+ sta _numbuf,y
+ sty sreg+2
+ beq digitloop ; branch always
+
+done:
+ rts