当有符号数乘以无符号数时

当有符号数乘以无符号数时

本文介绍了我应该使用“mul"吗?或“imul"当有符号数乘以无符号数时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 mulimul 都可以用来将有符号数乘以无符号数.

I have found out that both mul and imul can be used to multiply a signed number to an unsigned number.

例如:

global _start

section .data
    byteVariable DB -5

section .text
_start:

mov al, 2
imul BYTE [byteVariable]

您可以将 imul 替换为 mul,结果仍然相同(-10).

You can replace imul with mul, and the result would still be the same (-10).

有符号数乘以无符号数时,mulimul 是否完全相同,或者是它们之间有区别吗?

Are mul and imul exactly the same when multiplying a signed number to an unsigned number, or is there a difference between them?

推荐答案

上半部分不同,如评论中所述.如果你不关心上半部分,你可以使用 mulimul,在它们的所有形式中(单操作数形式产生上半部分,但在这种情况下,您将忽略它).

The upper half is different, as mentioned in the comments. If you don't care about the upper half, you can use either mul or imul, in all of their forms (the one-operand forms produce the upper half, but in this scenario you would ignore it).

如果你关心上半部分,mulimul 都不能自己工作,因为它们只是乘以无符号*无符号和有符号*有符号,但你可以修复它相当容易.

If you do care about the upper half, neither mul nor imul works by itself, since they just multiply unsigned*unsigned and signed*signed, but you can fix it fairly easily.

考虑有符号字节的位权重为 -128, 64, 32, 16, 8, 4, 2, 1 而无符号字节的位权重为 + 128, 64, 32, 16, 8, 4, 2, 1. 所以你可以用有符号格式表示 x 的无符号值(我知道这很令人困惑,但这是我能做的最好的)作为 x + 256 x_7(其中 x_7x 的第 7 位).最简单的查看方法可能是将其拆分:x + 2 * 128 * x_7.这里发生的事情是补偿-128 权重,首先通过将第 7 位的值相加 128 次来删除它,然后通过再次执行一直到 +128 权重,当然这可以一步完成.

Consider that a signed byte has the bit-weights -128, 64, 32, 16, 8, 4, 2, 1 while an unsigned byte has the bit-weights +​128, 64, 32, 16, 8, 4, 2, 1. So you can represent the unsigned value of x in signed format (I know this is confusing but it's the best I can do) as x + 256 x_7 (where x_7 is bit 7 of x). The easiest way to see is probably to split it: x + 2 * 128 * x_7. What's happening here is compensating for the -128 weight, first removing it by adding the value of bit 7 128 times and then going all the way up to the +128 weight by doing it again, of course this can be done in one step.

无论如何,将其乘以某个有符号数 y 并计算得出 256 x_7 y + xy,其中 xy 是 (double-width) imul256 x_7 y 的结果表示如果 x 的符号为将 y 添加到上半部分"> 已设置",因此可能的实现是(未测试)

Anyway, multiplying that by some signed number y and working it out gives 256 x_7 y + xy, where xy is the (double-width) result of imul and 256 x_7 y means "add y to the upper half if the sign of x is set", so a possible implementation is (not tested)

; al has some unsigned value
mov dl, al
sar dl, 7
and dl, [signedByte]
imul BYTE [signedByte]
add ah, dl

当然,您可以对一个操作数进行符号扩展,对另一个操作数进行零扩展,然后使用 16 位乘法(任意,因为上半部分与这种方式无关).

Naturally you could sign-extend one operand, zero-extend the other, and use a 16 bit multiplication (any, since the upper half is not relevant this way).

这篇关于我应该使用“mul"吗?或“imul"当有符号数乘以无符号数时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:23