Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ; Program to read a number and print its double
- section .data
- prompt db "Enter a number: ", 0
- prompt_len equ $ - prompt
- result db "Double of the number is: ", 0
- result_len equ $ - result
- newline db 10, 0
- section .bss
- num resb 32 ; Buffer to store input string
- output resb 32 ; Buffer to store output string
- section .text
- global _start
- _start:
- ; Print prompt
- mov rax, 1 ; sys_write
- mov rdi, 1 ; stdout
- mov rsi, prompt ; message to write
- mov rdx, prompt_len ; message length
- syscall
- ; Read input
- mov rax, 0 ; sys_read
- mov rdi, 0 ; stdin
- mov rsi, num ; buffer
- mov rdx, 32 ; buffer size
- syscall
- ; Convert string to integer using atoi
- mov rdi, num ; number string to convert
- call atoi ; call our atoi function
- ; Double the number
- add rax, rax ; multiply by 2
- ; Convert integer back to string
- mov rdi, output ; output buffer
- mov rsi, rax ; number to convert
- call itoa ; call our itoa function
- ; Print result message
- mov rax, 1 ; sys_write
- mov rdi, 1 ; stdout
- mov rsi, result ; message
- mov rdx, result_len ; length
- syscall
- ; Print the doubled number
- mov rax, 1 ; sys_write
- mov rdi, 1 ; stdout
- mov rsi, output ; converted number string
- mov rdx, 32 ; max length
- syscall
- ; Print newline
- mov rax, 1
- mov rdi, 1
- mov rsi, newline
- mov rdx, 1
- syscall
- ; Exit
- mov rax, 60 ; sys_exit
- mov rdi, 0 ; exit code 0
- syscall
- ; Function to convert ASCII string to integer (atoi)
- atoi:
- xor rax, rax ; zero out rax
- xor rcx, rcx ; zero out rcx
- .loop:
- movzx rdx, byte [rdi + rcx] ; get current char
- cmp dl, 0xa ; check for newline
- je .done
- cmp dl, 0 ; check for null terminator
- je .done
- sub dl, '0' ; convert ASCII to number
- imul rax, 10 ; multiply current result by 10
- add rax, rdx ; add new digit
- inc rcx ; move to next char
- jmp .loop
- .done:
- ret
- ; Function to convert integer to ASCII string (itoa)
- itoa:
- push rbp
- mov rbp, rsp
- sub rsp, 32 ; allocate stack space
- mov rax, rsi ; number to convert
- mov rcx, 0 ; digit counter
- mov r8, 10 ; divisor
- .divide_loop:
- xor rdx, rdx ; clear remainder
- div r8 ; divide by 10
- add dl, '0' ; convert to ASCII
- push rdx ; save digit
- inc rcx ; increment counter
- test rax, rax ; check if done
- jnz .divide_loop
- .build_string:
- mov rdx, rcx ; save length
- .digit_loop:
- pop rax ; get digit
- mov [rdi], al ; store in buffer
- inc rdi ; next position
- loop .digit_loop
- mov byte [rdi], 0 ; null terminate
- mov rsp, rbp
- pop rbp
- ret
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement