231 Simple Arithmetic in Assembly
--D. Thiebaut (talk) 07:57, 23 September 2014 (EDT)
simpleAdd.asm
;;; ----------------------------------------------------- ;;; simpleAdd.asm ;;; D. Thiebaut ;;; Simple program that adds 2 integers together. ;;; ;;; To assemble, link and run: ;;; nasm -f elf 231Lib.asm ;;; nasm -f elf simpleAdd.asm ;;; ld -melf_i386 simpleAdd.o 231Lib.o -o simpleAdd ;;; ./simpleAdd ;;; ----------------------------------------------------- ;;; extern functions that will be linked to this program ;;; contained in 231Lib.asm extern _printDec extern _printString extern _println extern _getInput ;;; ----------------------------------------------------- ;;; data section ;;; ----------------------------------------------------- section .data a dd 3 b dd 5 c dd 0 prompt db "> " ;;; ----------------------------------------------------- ;;; code section ;;; ----------------------------------------------------- section .text global _start _start: ;;; compute c = a + b; mov eax, dword[a] add eax, dword[b] mov dword[c], eax ;;; print c on the screen, as decimal number, then go to next line. mov eax, dword[c] call _printDec call _println ;;; ; exit mov ebx, 0 mov eax, 1 int 0x80
simpleAdd2.asm
- This version prompts the user to input both a, and b.
;;; ----------------------------------------------------- ;;; simpleAdd2.asm ;;; D. Thiebaut ;;; Simple program that prompts the user for 2 numbers and ;;; computes their sum. The result is printed on the screen. ;;; ;;; To assemble, link and run: ;;; nasm -f elf 231Lib.asm ;;; nasm -f elf simpleAdd2.asm ;;; ld -melf_i386 simpleAdd2.o 231Lib.o -o simpleAdd2 ;;; ./simpleAdd2 ;;; ----------------------------------------------------- ;;; extern functions that will be linked to this program ;;; contained in 231Lib.asm extern _printDec extern _printString extern _println extern _getInput ;;; ----------------------------------------------------- ;;; data section ;;; ----------------------------------------------------- section .data a dd 3 b dd 5 c dd 0 prompt db "> " ;;; ----------------------------------------------------- ;;; code section ;;; ----------------------------------------------------- section .text global _start _start: ;;; get 32-bit int a from user mov ecx, prompt ; display "> " mov edx, 2 call _printString call _getInput ; get int in eax mov dword[a], eax ; store in a ;;; get 32-bit int b from user mov ecx, prompt ; display "> " mov edx, 2 call _printString call _getInput ; get int in eax mov dword[b], eax ; store in b ;;; compute c = a + b; mov eax, dword[a] add eax, dword[b] mov dword[c], eax ;;; print c on the screen, as decimal number, then go to next line. mov eax, dword[c] call _printDec call _println ;;; ; exit mov ebx, 0 mov eax, 1 int 0x80