Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division of two numbers in NASM [duplicate]

Starting to teach myself assembly (NASM) I wanted to know how to divide 2 numbers (For instance on Windows).

My code looks like this but it crashes.

global _main
extern _printf

section .text

_main:

mov eax, 250
mov ebx, 25
div ebx
push ebx
push message 

call _printf
add esp , 8
ret

message db "Value is = %d", 10 , 0

I wonder what's really wrong? It doesn't even display the value after the division.

like image 557
Karen Avatar asked Aug 04 '17 12:08

Karen


People also ask

How does Div work in NASM?

div executes unsigned division. div divides a 16-, 32-, or 64-bit register value (dividend) by a register or memory byte, word, or long (divisor). The quotient is stored in the AL, AX, or EAX register respectively. The remainder is stored in AH, Dx, or EDX.

How do you divide in emu8086?

For division of a signed byte by signed byte, the numerator is stored in AL register and then it is sign extended to AH register. After division, the quotient goes to AL register and remainder is in AH register. The quotient value should in between +127 to 127 range otherwise it will generate divide error interrupt.


1 Answers

Your instruction div ebx divides the register pair edx:eax (which is an implicit operand for this instruction) by the provided source operand (i.e.: the divisor).


mov edx, 0
mov eax, 250
mov ecx, 25
div ecx

In the code above edx:eax is the dividend and ecx is the divisor. After executing the div instruction the register eax contains the quotient and edx contains the remainder.


I am using the register ecx instead of ebx for holding the divisor because, as stated in the comments, the register ebx has to be preserved between calls. Otherwise it has to be properly saved before being modified and restored before returning from the corresponding subroutine.


Divide by zero error may occur

As stated in one comment, if the quotient does not fit within the rage of the quotient register (eax in this case), a divide by zero error does occur.

This may explain why your program is crashing: since the register edx is not being set prior to executing the div instruction, it might contain a value so large, that the resulting quotient doesn't fit in the eax register.

like image 133
ネロク・ゴ Avatar answered Sep 29 '22 13:09

ネロク・ゴ