Search code examples
assemblydecimalnasmdivide

How do you round quotients when dividing in nasm?


im not sure if m using the wrong data types or the wrong instruction or what but div,idiv,fdiv all seem to give me a 0 for the quotient. And i want to get some decimal number rounded to a couple decimal places. i think im using the correct registers for the division too.

mov ebp, 3          ;ebp = 3(constant) 
mov eax, edx            ;eax = edx(sum from previous calculation)
mov ecx,3           ;load upper half of dividend with zero
div ecx             ;divide double register ecx eax by 3

push eax
push msg6
call _printf
add esp, 8

i changed the format in the printf so it displays in decimal format but there are still no numbers being divided it seems like?


Solution

  • mov ebp, 3          ;ebp = 3(constant)
    mov eax, edx        ;eax = edx(sum from previous calculation)
    mov ecx,3           ;load upper half of dividend with zero
    div ecx             ;divide double register ecx eax by 3
    

    It seems like your doing the division the wrong way! The code does not what the comments suggest.
    If EDX holds the sum from the previous calculation then you should move it into EAX but also clear EDX to prepare for the upcoming division.
    This is how the correct code looks:

    mov ebp, 3          ;ebp = 3(constant)
    mov eax, edx        ;eax = edx(sum from previous calculation)
    mov edx, 0          ;load upper half of dividend with zero
    div ebp             ;divide edx:eax by 3
    

    To work with 2 decimal places you can multiply by 100 prior to doing the division and then later insert a decimal point character before the last 2 characters of the result displayed as text.