Skip to content

Assembly x86_64 - Math operations

Assembly Code

We're going to use vim to write our code

[ 192.168.0.18/24 ] [ /dev/pts/88 ] [~/binexp/asm]
→ vim 5.asm




section .data
        digit db 0, 10

section .text
        global _start


_start:
        mov rbx, 48             ;48 in the ASCII chart is the "0" character
        call _printRAX          ;print "0" + 1
        call _printRAX          ;print "1" + 1
        call _printRAX          ;print "2" + 1
        call _printRAX          ;print "3" + 1
        call _printRAX          ;print "4" + 1

        mov rax, 60
        mov rdi, 0
        syscall



_printRAX:
        add rbx, 1              ; we increment rbx by 1 (48, 49, 50, 51, ...)
        mov [digit], rbx        ; we move the current value of rbx into the 'digit' memory address

        mov rax, 1              ; we use the syscall ID 1
        mov rdi, 1              ; we set the first arg to 1
        mov rsi, digit          ; the second arg is set to be our 'digit' memory address
        mov rdx, 2              ; the third arg is the length of 2 bytes (let's not forget the newline char which is the '10' above)
        syscall
        ret

Now let's check what's new in the code:

   mov [digit], rbx

Here we are moving the rbx register into the memory address that's referenced by the 'digit' label.

    mov rbx, 48  
        add rbx, 1          
        mov [digit], rbx

Now first we set the value of rbx to be 48, which is the "0" character in ascii. Then we want to add the value 1 to the value stored in rbx. and then we just move the rbx value into the memory address referenced by the 'digit' label

Basically our code should print the character 1, 2, 3, 4 and 5

Compiling

Here we're going to use nasm to compile our assembly code:

[ 192.168.0.18/24 ] [ /dev/pts/89 ] [~/binexp/asm]
→ nasm -f elf64 5.asm -o 5.o

[ 192.168.0.18/24 ] [ /dev/pts/89 ] [~/binexp/asm]
→ ld 5.o -o 5

[ 192.168.0.18/24 ] [ /dev/pts/89 ] [~/binexp/asm]
→ ./5
12345%

And that's it ! next tutorial we'll look into loops, you can click here.


Nihilist
Donate XMR to Nihilist:
8AUYjhQeG3D5aodJDtqG499N5jXXM71gYKD8LgSsFB9BUV1o
7muLv3DXHoydRTK4SZaaUBq4EAUqpZHLrX2VZLH71Jrd9k8