본문 바로가기

Programming Language/Assembly

[Assembly] 사칙연산 프로그램

실행환경

- cpu : 인텔계열(64bit)

- 컴파일러 : nasm

- 리눅스 : ubuntu 16.04 LTS


설치방법

sudo apt-get install nasm


컴파일

- nasm -f elf64 파일명.asm -o 파일명.o  --> 목적파일을 만든다.

- ld 파일명.o -o 파일명  --> 실행파일을 만든다.


calc.asm

section .data

first db "first : "

len1 equ $ -first

second db "second : "

len2 equ $ -second

operator db "operator : "

len3 equ $ -operator

end db 0ah

section .bss

num1   resb 5

num2   resb 5

op    resb 5

result resb 5

section .text

global _start


_start:

mov eax,4

mov ebx,1

mov ecx,first

mov edx,len1

int 0x80


mov eax,3

mov ebx,1

mov ecx,num1

mov edx,len1

int 0x80


mov eax,4

mov ebx,1

mov ecx,second

mov edx,len2

int 0x80


mov eax,3

mov ebx,1

mov ecx,num2

mov edx,len2

int 0x80


mov eax,4

mov ebx,1

mov ecx,operator

mov edx,len3

int 0x80


mov eax,3

mov ebx,1

mov ecx,op

mov edx,len3

int 0x80


mov al,[op]

cmp al,'+'

je addFunc

cmp al,'-'

je subFunc

cmp al,'*'

je mulFunc

cmp al,'/'

je divFunc

jmp exitFunc

addFunc:

mov al,[num1]

sub al,'0'

mov bl,[num2]

sub bl,'0'


add al,bl

add al,'0'

mov [result],al


mov eax,4

mov ebx,1

mov ecx,result

mov edx,1

int 0x80

call endFunc

jmp exitFunc

subFunc:

mov al,[num1]

sub al,'0'

mov bl,[num2]

sub bl,'0'


sbb al,bl

add al,'0'

mov [result],al

mov eax,4

mov ebx,1

mov ecx,result

mov edx,1

int 0x80


call endFunc

jmp exitFunc

mulFunc:

mov al,[num1]

sub al,'0'

mov bl,[num2]

sub bl,'0'


mul bl

add al,'0'

mov [result],al

mov eax,4

mov ebx,1

mov ecx,result

mov edx,1

int 0x80


call endFunc

jmp exitFunc


divFunc:

mov al,[num1]

sub al,'0'

mov bl,[num2]

sub bl,'0'


div bl

add al,'0'

mov [result],al

mov eax,4

mov ebx,1

mov ecx,result

mov edx,1

int 0x80


call endFunc

jmp exitFunc


endFunc:

mov eax,4

mov ebx,1

mov ecx,end

mov edx,1

int 0x80


exitFunc:

mov eax,1

int 0x80