Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modulo in assembly

Tags:

c

assembly

modulo

I've been trying for over 3 hours to figure out what's wrong with the next program. All I'm trying to do is to divide x in y, and then print the result of the division and the modulo. Also, the printf of the modulo, with the % inside, messes all up. Does anyone know how to fix that? I'm working on assembly IA32. Assume I get x and y from the user already.

.section    .rodata
format1:    .string "Div : %d / %d = %d\n"
format2:    .string "Mod : %d % %d = %d\n"

    .text
.globl  main    
    .type   main, @function 

# operation divide
movl    x,  %eax
cltd
idivl   y
pushl   %eax
pushl   y
pushl   x
pushl   $format1
call    printf

# operation modulo
pushl   %edx
pushl   y
pushl   x
pushl   $format2
call    printf

I know the modulo should be kept in the %edx register, so why it doesnt work? Thanks alot! D:

edit: Ok, so I saved %edx in %ebx and now the modulo works fine. (if I print what's in %edx it gives the right modulo) But the print to the screen still not what I want. This is the output for x=2, y=4:

Divide : 2 / 4 = 0
Modulo : 2 %d = 4

and I want it to look like this:

Divide : 2 / 4 = 0.50
Modulo : 2 % 4 = 2
like image 245
Jjang Avatar asked Jun 11 '26 00:06

Jjang


1 Answers

EAX, ECX and EDX are caller saved registers, this means you must save them before calling printf, which is at liberty to change any of those registers without restoring them.

EBX, ESI and EDI on the other hand are callee-saved, which means every function needs to restore them to their original contents before the call.

like image 95
phant0m Avatar answered Jun 13 '26 17:06

phant0m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!