2

I am trying to solve the equation: 7 * (4 + 10) + (15 / 5) for example in assembly language. I assume the BEDMAS principal still applies, but the code I run is not giving me the correct numerical value? I am not sure where I am going wrong. When we invoke DIV, does it not automatically divide the value from the AX register?

MOV BX,10
ADD BX,4
MOV AX,15
MOV BL,5
DIV BL
ADD AX,BX
MOV BX, 7
MUL BX
HLT
Sep Roland
  • 33,889
  • 7
  • 43
  • 76
  • The CPU has no idea of the formula you're trying to compute. It's up to you to generate the right sequence of operations for your computation. – Mat Nov 20 '18 at 17:02
  • would you be able to point me in the right direction of where am going wrong? I set the first bracket equation to the BX register, added the value of 5 to the BL register so I could divide the AX register, then I add them at the end and multiply BX by 7? or am I missing something? – Alexander Nov 20 '18 at 21:30
  • 1
    `div bl` does AL = AX/BL, and AH = AX%BL, like it says in the instruction-set reference manual (http://felixcloutier.com/x86/DIV.html). But `mov bl, 5` overwrites the low byte of BX. You might want to use CL for your divisor since you still have the `4+10` result in BX. Or do the division first. Use a debugger to single-step through your code. – Peter Cordes Nov 20 '18 at 23:10

1 Answers1

0
MOV BX,10
ADD BX,4
MOV AX,15
MOV BL,5          <<<< This overwrite the sum 10 + 4 in BX
DIV BL
ADD AX,BX         <<<< Luckily remainder was zero
MOV BX, 7
MUL BX            <<<< Needlessly clobbers DX

Apart from some other imperfections, this calculation does not even follow normal algebraic rules. You've calculated 7 * ( (4 + 10) + (15 / 5) ) when the task asked for ( 7 * (4 + 10) ) + (15 / 5)

  • On both division and multiplication use the accumulator, so inevitably you'll have to move the result from whichever of these you choose to do first in an extra register.
  • The byte sized division yields a quotient in AL but also a remainder in AH. This task asks you to continu with the quotient disregarding the remainder. Your code does not explicitely zero AH and that's not good enough for a generalized solution! Luckily 15 / 5 gave a remainder = 0.

Solution with division before multiplication:

mov ax, 15
mov bl, 5     ;Divider in BL
div bl        ;AX/BL -> AL=3 (remainder in AH=0)
mov bl, al    ;Move to an extra register
mov al, 4
add al, 10    ;AL=14
mov ah, 7
mul ah        ;AL*AH -> AX=98
add al, bl

Solution with multiplication before division:

mov al, 4
add al, 10    ;AL=14
mov ah, 7
mul ah        ;AL*AH -> AX=98
mov bh, al    ;Move to an extra register
mov ax, 15
mov bl, 5     ;Divider in BL
div bl        ;AX/BL -> AL=3 (remainder in AH=0)
add al, bh

Both solutions produce the same result (101) and use just 2 registers (AX and BX).

Sep Roland
  • 33,889
  • 7
  • 43
  • 76