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?
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).
-1 * 1 = -1
vs. 0xFFFFFFFF * 1 = 0xFFFFFFFF
. –
Shawanda imul rs, rd1[, rd2]
) while mul has only 1 form mul rx
–
Cadastre a * (uint64_t)b
if the inputs are narrower. It doesn't match reality for asm with widening multiply instructions. –
Slay 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).
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.
mul
. The only difference would be FLAGS setting, but that's needed rarely enough that Intel decided to only provide faster non-widening multiply as imul
opcodes. Related: C unsigned long long and imulq hinges on this decision: if you want an overflow-checked unsigned multiply, you unfortunately want one-operand mul
instead of trying to do something with FLAGS from imul reg,reg
. –
Slay © 2022 - 2024 — McMap. All rights reserved.
imul reg, r/m
instead of the one-operand widening form. And also How many least-significant bits are the same for both an unsigned and a signed multiplication? – Slay