Int to string conversion

Initially only binary output
This commit is contained in:
PleegWat
2026-09-08 17:00:26 +02:00
parent e654d451a7
commit 40e4272cdd
5 changed files with 154 additions and 1 deletions
+66
View File
@@ -0,0 +1,66 @@
include errno
; Convert integer to string
; Arguments:
; r1 - Integer
; r2 - Start of buffer
; r3 - Buffer length
; r4 - Base (2, 8, 10, or 16)
; Result:
; none
; Clobbers:
; Based on specialization
pub auto:
cmp r4, 2
je bin
mov flags, errno.INTTOSTR_BAD_BASE
jmp r13
; Convert integer to binary string
; Arguments:
; r1 - Integer
; r2 - Start of buffer (assumed 'big enough')
; r3 - Buffer length (ignored)
; Result:
; none
; Clobbers:
; flags
; r4 - counter
; r5 - result character
pub bin:
mov r4, 31
cmp r2, 2
jl badbuffer
bin_find_one:
lsr r5, r1, r4 ; Select bit and advance counter
and r5, r5, 1
sub r4, r4, 1
cmp r4, 0 ; Start printing if last bit ...
jl bin_print
cmp r5, zr ; .. or if nonzero
je bin_find_one
add flags, r4, 3 ; Check buffer size
cmp flags, r3
ja badbuffer
bin_print:
add r5, r5, 0x30 ; '0' ; Add digit to buffer
store_8 [r2], r5
add r2, r2, 1
cmp r4, 0 ; Done if last bit
jl done
lsr r5, r1, r4 ; Select bit and advance counter
and r5, r5, 1
sub r4, r4, 1
jmp bin_print
badbuffer:
mov flags, errno.INTTOSTR_BAD_BUFFER
jmp r13
done:
store_8 [r2], zr
jmp r13