51
Programming with NASM / Re: Printing numbers with stack as variable
« Last post by fredericopissarra on December 29, 2024, 05:40:49 PM »Would have been happy to know, why mine does not work es expectedTo push QWORDs with each character calculated in the first loop is a huge waste of stack space. It is simplier to pre-alocate the space (10 chars for a DWORD converted in decimal string), but keeping RSP QWORD (or DQWORD) aligned.
Here's your code modified:
Code: [Select]
bits 64
default rel
section .text
global _start
_start:
sub rsp,8+16 ; Align by DQWORD and reserve space to the string.
; We only need 11 bytes allocated, but we need to keep
; RSP aligned.
;
; Don't really need to keep RSP aligned to DQWORD in this
; code, but it is a good practice in case we use SSE/SSE2.
mov rsi,rsp ; Using RSI because sys_write needs it.
mov eax, 1234 ; # to print.
xor ecx, ecx ; Counter = 0.
mov byte [rsi],`\n`
mov ebx, 10
align 4
.loop:
dec rsi
xor edx, edx
div ebx
add dl, '0'
mov [rsi],dl
inc rcx ; Increment counter.
test eax, eax ; Quotient == 0?
jnz .loop ; No, stay in the loop.
; sys_write.
mov eax,1
mov edi,eax
lea edx,[rcx+1] ; The final '\n' as well.
syscall
add rsp,8+16 ; Restore RSP to its original position.
; Not really needed since sys_exit will not return.
; FIXED: Use 'syscall', not 'int 0x80'.
mov eax, 60
xor edi, edi
syscall
Recent Posts