问题描述
假设以下代码:
mov eax, 0
sub eax, 2
xor edx, edx
idiv base
其中 base
等于8(定义为 const int base = 8
)。
where base
equals to 8 (defined as const int base = 8
).
因此,我希望在 eax
中得到0,在 edx
中得到2(或−2)。但是,划分的结果是一个很大的长期数字。很有可能是由 eax
注册表溢出引起的,当我从中减去2时。我认为 eax
被 idiv
操作解释为 unsigned int
。如何正确执行此除法?
As a result, I expect to get 0 in eax
and 2 (or −2) in edx
. However, the result of the division is a big long number. Most likely, it is caused by overflow in eax
registry, when I subtract 2 from it. I think eax
is interpreted by idiv
operation as unsigned int
. How do I perform this division properly?
我在x64系统上的Visual Studio 2013中编写代码。
I code in Visual Studio 2013 on x64 system.
推荐答案
通常的原因: edx
应该是64位股息的上半部分。因此,如果您有一个负数,则 edx
不能为零(至少必须设置符号位,否则它不是负数),并且您有32位符号数字,您必须将其符号扩展到 edx:eax
。
The usual reason: edx
is supposed to be the "upper half" of a 64bit dividend. So if you have a negative number, edx
can not be zero (at least the sign bit must be set, otherwise it's just not negative), and if you had a 32bit signed number, you have to sign-extend it into edx:eax
.
cdq
指令确实如此,所以很容易:
Which is what the cdq
instruction does, so it's easy:
mov eax, -2
cdq
idiv base
这篇关于将负数与正数相除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!