问题
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.
assume the system uses 2's complement and a 32-bit representation of ints
回答1:
Try performing the subtraction with 32-bit and 64-bit.
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: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
来源:https://stackoverflow.com/questions/23159020/integer-overflow-with-subtraction