I thought the whole point of 2's complement was that operations could be implemented the same way for signed and unsigned numbers. Wikipedia even specifically lists multiply as one of the operations that benefits. So why does x86 have separate instructions for each, mul
and imul
? Is this still true for x86-64?
3 Answers
Addition and subtraction are the same, as is the low-half of a multiply. A full multiply, however, is not. Simple example:
In 32-bit twos-complement, -1 has the same representation as the unsigned quantity 2**32 - 1. However:
-1 * -1 = +1
(2**32 - 1) * (2**32 - 1) = (2**64 - 2**33 + 1)
(Note that the low 32-bits of both results are the same; that's what I mean when I say the "low-half of the multiply" is the same).
Multiplication of two 16-bit numbers yields a 32-bit result. Even if one of the numbers is "1", the processor will effectively extend the other to 32 bits. The process of extending a number to a longer bit length is one of the operations which is different for signed and unsigned values (the other significant operation where sign matters is magnitude comparison, which is also an essential part of division).