作为谜题的一部分,我被要求实现一个函数,该函数检查两个整数是否可以加在一起而不会溢出。法律行动:!~ & ^ | + << >>。
例如,对于 x = 0x80000000 和 y = 0x80000000,函数应该返回 0,因为它溢出,但对于 x = 0x80000000 和 y = 0x70000000,结果将是 1。
到目前为止,我的解决方案是:
int addOK(int x, int y) {
int mask = ~(1 << 31); // 0x7fffffff
int newX = (mask & (x >> 1)); // Shift 1 to the right to make space for overflow bit
int newY = (mask & (y >> 1));
int add = newX + newY; // Add shifted x and y - overflow bit will be the MSB
int res = (add & ~mask); // Set all bits to 0 except MSB - MSB 1 iff overflow 0 otherwise
int endRes = !res; // 0x80000000 -> 0x00000000, 0x00000000 -> 0x00000001
printf("mask %x newX %x newY %x add %x ~mask %x res %x endRes %x\n",mask, newX, newY, add, ~mask, res, endRes);
return endRes;
}
对于 x = 0x80000000 和 y = 0x80000000,该函数打印以下内容:
mask 7fffffff newX 40000000 newY 40000000 add 80000000 ~mask 80000000 res 0 endRes 1
现在我的问题是为什么是res
0?它应该是 0x80000000,因为add
和~mask
都是 0x80000000。谁能向我解释这种行为?