I tried it and I think this should work but I think I am calling it wrong I have no Idea where my error is . Here is my code :
;------------------------------------------
; int atoi(Integer number)
; Ascii to integer function (atoi)
;%include "functions.asm"
section .data
MSG: db "Input number : ",10
MSG_L: equ $ - MSG
section .bss
x_number resb 255
section .text
global _start:
_start:
mov rdx, MSG_L ;length
mov rsi, MSG;variable
mov rdi,1;sys_write
mov rax, 1;stdout
syscall
mov rdx, 255
mov rsi, x_number
mov rdi, 0
mov rax, 0
syscall
mov rdi, x_number
call atoi
mov rdx, 0
mov rcx, 16
div rcx
mov qword [x_number], rax
mov rdi, x_number
call itoa
mov rax, 60
mov rdi, 0
syscall
ret
atoi:
push rbx;if you are going to use rbx you must preserve it by pushing it onto the stack
;~ Address is passed in rdi
mov rbx, 10 ; to multiply by
xor rax, rax; to use as "result so far"
xor rcx, rcx ; our character/digit (high bits zero)
.top:
mov cl, byte [rdi] ; get a character
add rdi, 1 ; get ready for the next one
cmp cl, 0 ; end of string?
je .done
cmp cl, '0'
jb .invalid
cmp cl, '9'
ja .invalid
sub cl, '0' ; or 48 or 30h
; now that we know we have a valid digit...
; multiply "result so far" by 10
mul rbx
jc .overflow ; ?
; and add in the new digit
add rax, rcx
jmp .top
; I'm not going to do anything different for overflow or invalid
; just return what we've got
.overflow:
.invalid:
.done:
pop rbx;restore rbx to its original value
ret ; number is in rax
itoa:
push rbx
mov rbx, 10
;puts a zero before everything so that in the next loop it will know when to stop
dec rdi
mov byte [rdi], 0
inc rdi
.top:;loops through to the end so that rdi points to the end
mov cl, byte [rdi]
inc rdi
cmp rdi, 0
je .next
jmp .top
xor rax, rax;clears out rax just in case
xor rdx, rdx;clearing out rdx just incase
.next:
mov al, byte [rdi];moves the next character into al
div rbx;divide by ten
add rdx, '0';convert to ASCII
mov rdx, 1 ;length
mov rsi, rdx;variable
mov rdi,1;sys_write
mov rax, 1;stdout
syscall
cmp byte [rdi], 0;is it the end?
je .done;f so jup to done
dec rdi;get ready for the next character
jmp .next
.done:
pop rbx
ret
It is seg faulting , looks like I cause a lot of those lol