整数溢出与减法 [英] Integer overflow with subtraction
问题描述
好了,所以我需要实现取决于返回零或一个方法,如果溢出X-Y的结果。
Okay so I need to implement a method that returns zero or one depending on if x-y results in an overflow.
Example: subTract(0x80000000,0x80000000) = 1,
subTract(0x80000000,0x70000000) = 0,
我不是在寻找这种方法的实现。我不明白哪一个假想导致溢出,这使得它几乎无从下手。为什么其中一个导致溢出?什么定义了减法溢出。
I'm NOT looking for an implementation of this method. I don't understand which one supposedly results in an overflow, and that making it nearly impossible to start. Why does one of these cause an overflow? What defines an overflow with subtraction.
假设系统使用2的补数和整数的32位重presentation
assume the system uses 2's complement and a 32-bit representation of ints
推荐答案
尝试用32位和64位执行减法。
Try performing the subtraction with 32-bit and 64-bit.
1:无溢出。 XX
的区别是 0
并重新presentable作为32位 INT
。不管什么整数值/类型这是预期 X
的可能。
1:No overflow. The difference of x-x
is 0
and is representable as a 32-bit int
. This is expected regardless of what integer value/type x
may be.
0:溢出。 XY
的差异(或 -2147483648 - 1879048192
)的算术 -4026531840
是的不的再presentable作为32位 INT
。下面code的结果提供了的差异268435456
。但 INT
溢出是未定义行为,所以这里的结果可能在另一台机器上的不同。
0:Overflow. The difference of x-y
(or -2147483648 - 1879048192
) is arithmetically -4026531840
and is not representable as a 32-bit int
. The result of the below code provided a difference of 268435456
. But int
overflow is undefined behavior, so the result here may differ on another machine.
溢出与减法当算术正确差不匹配所计算的差异发生。
Overflow with subtraction occurs when the arithmetically correct difference does not match the computed difference.
void subtest(void) {
int32_t x = 0x80000000;
int32_t y = 0x70000000;
printf("x = %" PRId32 "\n", x);
printf("y = %" PRId32 "\n", y);
printf("x-x = %" PRId32 "\n", x-x);
printf("x-y = %" PRId32 "\n\n", x-y);
int64_t x2 = x;
int64_t y2 = y;
printf("x2 = %" PRId64 "\n", x2);
printf("y2 = %" PRId64 "\n", y2);
printf("x2-x2 = %" PRId64 "\n", x2-x2);
printf("x2-y2 = %" PRId64 "\n", x2-y2);
}
x = -2147483648
y = 1879048192
x-x = 0
x-y = 268435456
x2 = -2147483648
y2 = 1879048192
x2-x2 = 0
x2-y2 = -4026531840
这篇关于整数溢出与减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!