Splitting two numbers in NASM

Starting to teach myself assembly (NASM), I wanted to know how to divide 2 numbers (for example, 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

      

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

+3


source to share


2 answers


Your instruction div ebx

divides a pair of registers edx:eax

(which is an implicit operand for this instruction) with the supplied source operand (i.e.: a divisor).




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

      

The above code edx:eax

has a dividend and ecx

a divisor. After the command is executed, the div

register eax

contains the factor and edx

contains the remainder.




I use register ecx

instead ebx

to store the divisor because, as pointed out in the comments , the register ebx

must be preserved between calls. Otherwise, it must be correctly saved before being modified and restored before returning from the appropriate subroutine.




Division by zero error may occur

As pointed out in one comment , if the factor doesn't fit into the rage of the factor register ( eax

in this case), divide by zero error.

This may explain why your program is crashing: since the register is edx

not set before executing the command div

, it can contain such a large value that the resulting factor is not suitable for eax

.

+4


source


The other comments and answers explain how to use div correctly, but they don't explain why your code is crashing rather than printing the wrong result. In most assemblers, "push message" pushes the first 4 bytes of the message, not the message address, which is what printf expects. In NASM, as far as I can tell, it pushes the address. But you have to double check this as I am not using NASM.



-2


source







All Articles