Use native div instructions for itoa

This commit is contained in:
Bill Rossi 2023-12-21 10:10:30 -05:00
parent ffface8b0a
commit a3d01d5873

View File

@ -1,58 +1,49 @@
;; rax contains the integer ;; rax contains the integer
;; rbx contains a pointer to the string buffer ;; rbx contains a pointer to the string buffer
itoa: itoa:
mov byte [rbx], '0'
;; Special case for the number '0' ;; Special case for the number '0'
cmp rax, 0 cmp rax, 0
jne .not_zero jne .not_zero
mov byte [rbx], '0'
mov byte [rbx + 1], 0 mov byte [rbx + 1], 0
ret ret
.not_zero: .not_zero:
;; Fill 6 digits with zeroes mov rdx, 0
mov byte [rbx + 1], '0' mov rcx, 100000
mov byte [rbx + 2], '0' div rcx
mov byte [rbx + 3], '0' add rax, '0'
mov byte [rbx + 4], '0' mov [rbx], al
mov byte [rbx + 5], '0'
sub rax, 100000 mov rax, rdx
inc byte [rbx] mov rdx, 0
cmp rax, 0 mov rcx, 10000
jge itoa div rcx
add rax, 100000 add rax, '0'
dec byte [rbx] mov [rbx + 1], al
.ten_thousand:
sub rax, 10000
inc byte [rbx + 1]
cmp rax, 0
jge .ten_thousand
add rax, 10000
dec byte [rbx + 1]
.one_thousand:
sub rax, 1000
inc byte [rbx + 2]
cmp rax, 0
jge .one_thousand
add rax, 1000
dec byte [rbx + 2]
.one_hundred:
sub rax, 100
inc byte [rbx + 3]
cmp rax, 0
jge .one_hundred
add rax, 100
dec byte [rbx + 3]
.ten:
sub rax, 10
inc byte [rbx + 4]
cmp rax, 0
jge .ten
add rax, 10
dec byte [rbx + 4]
add [rbx + 5], rax
mov rax, rdx
mov rdx, 0
mov rcx, 1000
div rcx
add rax, '0'
mov [rbx + 2], al
mov rax, rdx
mov rdx, 0
mov rcx, 100
div rcx
add rax, '0'
mov [rbx + 3], al
mov rax, rdx
mov rdx, 0
mov rcx, 10
div rcx
add rax, '0'
mov byte [rbx + 4], al
add dl, '0'
mov byte [rbx + 5], dl
;; Time to shift everything left ;; Time to shift everything left
;; End the current string with a null byte ;; End the current string with a null byte