I'm still new to assembly code on NASM for x86-64 Linux system and I'm trying to write a program which converts the number stored in rdi to decimal so it can be printed. I'm unsure how to write a proper function that will divide by 10 in a loop that uses the remainder as the digits for example: the number 165 stored in rdi will be divided 165/10 repeatedly and the remainder is 5, etc. and the digits output would look something to 0000000165. Any feedback would be appreciated! Here's my attempt:
section .data
BUFLEN: equ 25
buf: times BUFLEN db 0
section .text
global _start
_start:
mov rsi, 1
mov rdi, 453265682
call printnum
mov rax, 60
mov rdi, 0
syscall
printnum:
mov r10, 10
convert:
mov rdx, 0
mov rax, rdi
div r10
add r15, rdx
cmp rax, 1
jnle convert
mov rax, 1 ; = 1
mov rdi, 1 ; = 1
mov rsi, buf ; add of buffer to print
mov rdx, BUFLEN ; num of bytes to write
syscall
ret
CodePudding user response:
There are so many parts in your code that I want to change, but here is a minimal fix to just make your code work.
Below
mov r10, 10
add
mov r15, 9
Erase
add r15, rdx
cmp rax, 1
jnle convert
and change it to
mov rdi, rax
add rdx, '0'
mov [r15 buf], dl
dec r15
jns convert
This is the full printnum
function with the fix.
printnum:
mov r10, 10
mov r15, 9
convert:
mov rdx, 0
mov rax, rdi
div r10
mov rdi, rax
add rdx, '0'
mov [r15 buf], dl
dec r15
jns convert
mov rax, 1
mov rdi, 1
mov rsi, buf
mov rdx, BUFLEN
syscall
ret
It's up to you to think why this works and yours doesn't.