I was instructed to write a program in assembly that will carry out the following arithmetic:
((A + B) / C) * ((D - A) + E)
I've succeeded in doing this when no negative values come into to play, but suppose A = 5, B = 4, C = 3, D = 2, and E = 1. This gives us ((5 + 4) / 3) * ((2 - 5) + 1) or -6.
this is where I need help. I've done some research, and have found 2's compliment to be a solution, but I'm not sure to implement it into my code.
If someone could help me, I'd be very grateful!
INCLUDE Irvine32.inc ; ((A + B) / C) * ((D - A) + E) .data valA dword 1 valB dword 2 valC dword 3 valD dword 4 valE dword 5 .code main PROC mov ecx, valA add ecx, valB mov edx, valC call Divide mov ecx, eax mov edx, valD sub edx, valA add edx, valE call Multiply exit main ENDP
*Divide and Multiply Procedures divide and multiply respectively.
On a twos complement machine,
add
andsub
operations are actually the same for signed and unsigned quantities, so those parts of your program don't need to change. There are specific instructions for signed division and multiplication, so make sure the functions use those (or just use them directly).Irvines's
WriteDec
should be replaced byWriteInt
which handles the argumentEAX
as signed number.Inside the CPU, the negative "-2" and the positive "4294967294" are transformed to the same value: 0xFFFFFFFE.
DIV
performs the division 6/-2 positively (6/4294967294) and gets the result 0 = 0x00000000, withIDIV
the result is correct: -3 = 0xFFFFFFFD.MUL
andIMUL
differ in the high part of the result (EDX
). Since the high part is not needed in this case, it is not mandatory to useIMUL
.There are no different versions of
ADD
andSUB
for signed and unsigned numbers. This was the main reason for introducing the 2's complement coding. It's just a thing of interpretation: if the programmer decides that this should be a signed number, then it is a signed number. If he/she/it decides that this is an unsigned number, then it is an unsigned number. The CPU doesn't care about such things - the results will be always the same.Here's an example with
WriteInt
,IDIV
andIMUL
:A 2's complement calculation is needed to get the absolute value of the number. E.g. the representation of -2 has two parts: a sign ('-') and an absolute value ('2'). A simple way to get the absolute value is to look at the sign bit, the leftmost bit of the number, and to jump appropriate. The calculation itself is performed just by
NEG
.Example with
WriteDec
,IDIV
andIMUL
:Here is an algorithm to get the absolute value of EAX without jump: