0

I need to divide the sum of two arrays, but it results in a float number (0.73). How would I go about dividing two variables and storing the float number in register. Then multiplying the float number by 100 to turn it into an integer (73). The following results in EAX = 00000000

.386
.model flat, stdcall
.stack 4096
ExitProcess PROTO, dwExitCode: DWORD

.data
    AR1 DB 25, 89, 49, 80
    AR2 DB 30, 100, 50, 150
    AR1_SUM DWORD 0   ; variable to store the sum of AR1 elements
    AR2_SUM DWORD 0   ; variable to store the sum of AR2 elements


.code
_main PROC
    
    mov esi, offset AR1 ; set ESI to point to the first element of AR1
    mov ecx, 4 ; reset the loop counter
    xor edx, edx ;

    addloop1:
        add dl, [esi] ; add the current byte to the sum
        add esi, 1 ; move to the next byte in AR1
        loop addloop1 ; repeat until all elements in AR1 have been added
    mov AR1_SUM, edx
    
    mov esi, offset AR2 ; set ESI to point to the first element of AR2
    mov ecx, 4 ; reset the loop counter
    xor edx, edx ; reset the sum register for AR2

    addloop2:
        add dl, [esi]
        adc dh, 0
        add esi, 1 ; move to the next byte in AR2
        loop addloop2 ; repeat until all elements in AR2 have been added
    mov AR2_SUM, edx ; store the sum of AR2 in AR2_SUM

    mov eax, AR1_SUM 
    mov ebx, AR2_SUM 
    xor edx, edx
    div ebx

    INVOKE ExitProcess, 0

_main ENDP
END _main
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Evan
  • 13
  • 3
  • 1
    You want to multiply first then divide to avoid floats. – Jester Mar 28 '23 at 23:22
  • Integer division truncates the result (and produces a remainder, which isn't directly useful for printing as a decimal fraction). It doesn't magically store a floating-point value in the integer register EAX. https://www.felixcloutier.com/x86/div – Peter Cordes Mar 29 '23 at 03:22
  • @Jester: Is there a canonical duplicate for this? I know we've had questions before where people wanted a decimal fraction and the answer was to multiply by 100 before dividing. [Assembly equation, Divide to get float value](https://stackoverflow.com/q/49267371) includes that idea buried in other stuff. Ah, [division issue with registers in inline asm](https://stackoverflow.com/q/23173884) looks viable, exact duplicate except for the distraction of inline asm. – Peter Cordes Mar 29 '23 at 03:27

0 Answers0