I’m currently learning assembly language and trying to write a simple calculator program. The program is supposed to read two numbers and an operator (+, -, *, /) from stdin, perform the specified operation, and print the result. However, I’m encountering some issues with the IMUL and DIV instructions in my code. Here’s what I have so far
section .bss
num1 resb 8 ; Buffer to store the first number (max 8 bytes)
num2 resb 8 ; Buffer to store the second number (max 8 bytes)
operator resb 1 ; Buffer to store the operator (1 byte)
result resb 16 ; Buffer to store the result (max 16 bytes)
section .text
global _start
_start:
; Read the first number
mov rax, 0 ; syscall number (sys_read)
mov rdi, 0 ; file descriptor (stdin)
mov rsi, num1 ; buffer to store input
mov rdx, 8 ; number of bytes to read (max 8 bytes)
syscall ; call kernel
; Read the operator
mov rax, 0 ; syscall number (sys_read)
mov rdi, 0 ; file descriptor (stdin)
mov rsi, operator ; buffer to store input
mov rdx, 1 ; number of bytes to read (1 byte)
syscall ; call kernel
; Read the second number
mov rax, 0 ; syscall number (sys_read)
mov rdi, 0 ; file descriptor (stdin)
mov rsi, num2 ; buffer to store input
mov rdx, 8 ; number of bytes to read (max 8 bytes)
syscall ; call kernel
; Convert first number from ASCII to integer
movzx eax, byte [num1]
sub eax, '0'
; Convert second number from ASCII to integer
movzx ebx, byte [num2]
sub ebx, '0'
; Perform the specified operation
mov cl, byte [operator]
cmp cl, '+'
je add_operation
cmp cl, '-'
je sub_operation
cmp cl, '*'
je mul_operation
cmp cl, '/'
je div_operation
add_operation:
add eax, ebx
jmp output
sub_operation:
sub eax, ebx
jmp output
mul_operation:
imul eax, ebx
jmp output
div_operation:
xor edx, edx
div ebx
jmp output
output:
add eax, '0'
mov [result], al
mov [result+1], 0 ; null terminator for safety
mov rax, 1 ; syscall number (sys_write)
mov rdi, 1 ; file descriptor (stdout)
mov rsi, result ; buffer to store output
mov rdx, 2 ; number of bytes to write (result + null terminator)
syscall ; call kernel
; Exit
mov rax, 60 ; syscall number (sys_exit)
xor rdi, rdi ; exit code 0
syscall ; call kernel
When I run this code, I get the following errors:
main.asm:60: error: invalid combination of opcode and operands
main.asm:71: error: operation size not specified
I am not sure how to fix these issues. Any help would be greatly appreciated!
권민서 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.