Skip to content
Advertisement

How can I create a basic NASM Assembly (Linux) calculator to add two integers?

I had a go at it, and tried:

section .data
promptmsg: db 'Enter integer: '
msgsize: equ $-promptmsg

section .bss       ;creating variables to store input
firstnum: resb 6
secondnum: resb 6

section .text
global _start

_start:

xor eax, eax
xor ebx, ebx
xor ecx, ecx
xor edx, edx

mov eax, 4          ;system call to write
mov ebx, 1
mov ecx, promptmsg
mov edx, msgsize
int 80h

xor eax, eax
xor ebx, ebx
xor ecx, ecx
xor edx, edx

mov eax, 3               ;system call to read
mov ebx, 0
mov ecx, firstnum
mov edx, 6
int 80h

push firstnum

xor eax, eax
xor ebx, ebx
xor ecx, ecx
xor edx, edx

mov eax, 4              ;system call to write
mov ebx, 1
mov ecx, promptmsg
mov edx, msgsize
int 80h

xor eax, eax
xor ebx, ebx
xor ecx, ecx
xor edx, edx

mov eax, 3                ;system call to read
mov ebx, 0
mov ecx, secondnum
mov edx, 6
int 80h

push secondnum

xor eax, eax
xor ebx, ebx
xor ecx, ecx
xor edx, edx

pop eax
pop ebx
add eax, ebx         ;attempt to add firstnum and secondnum and store in EAX

push eax

xor eax, eax
xor ebx, ebx
xor ecx, ecx
xor edx, edx

mov eax, 4          ;once again a system call to write
mov ebx, 1
pop ecx
mov edx, 7
int 80h

xor eax, eax
xor ebx, ebx
xor ecx, ecx
xor edx, edx

mov eax, 1             ;exit safely and return 0
mov ebx, 0
int 80h

Sorry about all the XOR instructions, I just wanted to make sure registers were cleared before I used them for a system call, I’m still learning assembly and not sure about what instructions will render a register empty.

When I compile, link and run this I can enter the two integers only if I include the ENTER character, i.e. newline character. An integer can’t be added to it, so already that causes a problem. So when I enter both of them, I get no further output on the screen from the program, and the it just ends.

How can I correct it?

(Using C or C++ with ASM is not an option in this case.)

Advertisement

Answer

It’s not about “correcting” your code as it is about writing a missing part of it.

You have to parse integers, ignoring separating whitespace. Add them, then convert a result into a string. Then output this string. Calling scanf or strtol or printf is probably inacceptable to you, as it’s using a standard C library.

Advertisement