0

I'm a novice Assembly x86 Learner, and i want to add two numbers (5+5) and print the result on the screen.

here is my code:

global _start

section .text
_start:
    mov eax, 5
    mov ebx, 5
    add eax, ebx
    push eax
    mov eax, 4 ; call the write syscall
    mov ebx, 1 ; STDOUT
    pop ecx    ; Result
    mov edx, 0x1
    int 0x80

    ; Exit
    mov eax, 0x1
    xor ebx, ebx
    int 0x80

Correct me please

rkhb
  • 14,159
  • 7
  • 32
  • 60
Th3carpenter
  • 201
  • 1
  • 4
  • 16

1 Answers1

4

Another approach to convert an unsigned integer to a string and write it:

section .text
global _start
_start:

    mov eax, 1234567890
    mov ebx, 5
    add eax, ebx

    ; Convert EAX to ASCII and store it onto the stack
    sub esp, 16             ; reserve space on the stack
    mov ecx, 10
    mov ebx, 16
    .L1:
    xor edx, edx            ; Don't forget it!
    div ecx                 ; Extract the last decimal digit
    or dl, 0x30             ; Convert remainder to ASCII
    sub ebx, 1
    mov [esp+ebx], dl       ; Store remainder on the stack (reverse order)
    test eax, eax           ; Until there is nothing left to divide
    jnz .L1

    mov eax, 4              ; SYS_WRITE
    lea ecx, [esp+ebx]      ; Pointer to the first ASCII digit
    mov edx, 16
    sub edx, ebx            ; Count of digits
    mov ebx, 1              ; STDOUT
    int 0x80                ; Call 32-bit Linux

    add esp, 16             ; Restore the stack

    mov eax, 1              ; SYS_EXIT
    xor ebx, ebx            ; Return value
    int 0x80                ; Call 32-bit Linux
rkhb
  • 14,159
  • 7
  • 32
  • 60
  • 1
    You could optimize this to `mov ebx, esp` *before* `sub esp, 16`, then store with `dec ebx` / `mov [ebx], dl`. Or to `lea ebx, [esp+16]` to make the end-of-buffer thing more explicit. Or better, use ECX for that in the first place, so the pointer to the first (in printing order) digit will already be in ECX for the `int 0x80`. I did the 64-bit `syscall` equivalent of that in [How do I print an integer in Assembly Level Programming without printf from the c library?](https://stackoverflow.com/a/46301894) – Peter Cordes Nov 23 '21 at 05:29