Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are signed and unsigned multiplication different instructions on x86(-64)?

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?

like image 537
Joseph Garvin Avatar asked Dec 28 '12 01:12

Joseph Garvin


People also ask

What is the difference between signed and unsigned multiplication?

The main difference between a signed and an unsigned number is, well, the ability to use negative numbers. Unsigned numbers can only have values of zero or greater. In contrast, signed numbers are more natural with a range that includes negative to positive numbers.

What is signed and unsigned integer in assembly language?

Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges. Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive.


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).

like image 51
Stephen Canon Avatar answered Oct 23 '22 06:10

Stephen Canon


The result will be the same for the 2 and 3 operand versions except that the mul and imul instructions differ in how they set the CF and OF flags (carry and overflow).

Think of the two cases: -1 * -1 versus 0xFFFFFFFF * 0xFFFFFFFF in terms of overflow and you'll get the idea.

like image 23
Scott Conger Avatar answered Oct 23 '22 06:10

Scott Conger


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).

like image 26
supercat Avatar answered Oct 23 '22 07:10

supercat