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

ぃ、小莉子 提交于 2019-11-26 08:52:33

问题


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?


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/14063599/why-are-signed-and-unsigned-multiplication-different-instructions-on-x86-64

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!