Evaluating this in Assembly (A % B) % (C % D)

45 views Asked by At
INCLUDE Irvine32.inc
INCLUDELIB Irvine32.lib
INCLUDELIB kernel32.lib
INCLUDELIB user32.lib

.data
    A  SBYTE 10d ; A is an 8-bit signed integer
    B  SBYTE 2d  ; B is an 8-bit signed integer
    cc SBYTE 20d ; C is an 8-bit signed integer
    D  SBYTE 5d  ; D is an 8-bit signed integer

.code
main PROC
    mov EAX, 0
    mov EDX, 0

    mov al, A  ; Load A into AL register
    
    imul B
    movsx bx, cc
    imul bx
    movsx bx, D
    imul bx

    call DumpRegs ;
 
exit
main ENDP
END main

I have this code and I want to modify it to print output for this (A % B) % (C % D) but when I use idiv the code doesn't give any outputs.

1

There are 1 answers

0
Sep Roland On
mov al, A  ; Load A into AL register
imul B
movsx bx, cc
imul bx
movsx bx, D
imul bx

This code calculates A * B * cc * D, simply multiplying the 4 numbers.

but when I use idiv the code doesn't give any outputs.

You can't just substitute that instruction: imul outputs to AH / DX / EDX / RDX, where idiv inputs from AH / DX / EDX / RDX. You need to develop a new solution from scratch.

The solution for this task must not only use the division instruction, but also respect the algebraic order of things as indicated by the parenthesis.
Although the 4 variables were defined as signed integers, I see their values are all positive numbers. Therefore I will present a solution that uses the div instruction. I would hate to take the fun away, so I will leave the signed version of this up to you...

.data
    A  BYTE 10
    B  BYTE 2
    C  BYTE 20
    D  BYTE 5

.code
main PROC
    ; (C % D)
    movzx ebx, D
    test  bl, bl
    jz    ERROR     ; #DE can't divide by zero
    movzx eax, C
    xor   edx, edx
    div   ebx       ; EDX:EAX / EBX --> EDX is remainder
    test  edx, edx
    jz    ERROR     ; #DE can't divide by zero          (*)
    mov   ecx, edx
    
    ; (A % B)
    movzx ebx, B
    test  bl, bl
    jz    ERROR     ; #DE can't divide by zero
    movzx eax, A
    xor   edx, edx
    div   ebx       ; EDX:EAX / EBX --> EDX is remainder
    
    ; (A % B) % (C % D)
    mov   eax, edx
    xor   edx, edx
    div   ecx       ; EDX:EAX / ECX --> EDX is remainder
    
    ; Result is in EDX

With the current data set, the program errors out at the asterisk!