Question

I am making a virtual machine and a C compiler for it. Something I do not get though is how most instruction sets have a IMUL and IDIV but not a ISUB and an IADD. Since sub is usually unsigned sub how could I do something like in x86

MOV EAX,1
MOV EDX,3
SUB EAX,EDX,EAX

and get -2?

Was it helpful?

Solution

Signed addition always produces the same bit patterns as output as unsigned addition -- only the interpretation of them is different -- so there is no need to have separate instructions for the two cases. It's the same for subtraction.

The general ADD and SUB instructions set two groups of condition flags such that you can later check for the outcome of a SUB-based comparison using ja/jb for unsigned comparisions or jg/jl for signed ones.

(More precisely: If you already have instructions that do unsigned addition/subtraction modulo 2^wordlen, then the bit patterns they produce will be correct for every 2's complement signed addition/subtraction whose true result is representable. Mathematically this is because unsigned integers and 2's complement signed integers are just different choices of canonical representatives of residue classes modulo 2^wordlength).

OTHER TIPS

There is only one instruction of each, as subtraction and addition yields the same result regardless of the arguments being signed or unsigned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top