gpt4 book ai didi

C++ 负数左移溢出

转载 作者:太空宇宙 更新时间:2023-11-04 00:57:11 30 4
gpt4 key购买 nike

如下图,代码有bug。当输入 a = -1, b = 1 时,其中一行出现运行时错误。你能帮我理解 (a & b) 是如何变成 INT_MIN 的吗?

在我的理解中,-1表示为32位二进制格式0xFFFFFFFF,1表示为32位格式0x00000001,因此(-1 & 1)将变为0x00000001。结果我的 python 命令也显示“0b1”。为什么会报INT_MIN的错误?

int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;//BUG! left shift of negative value -2147483648
a = a ^ b;
b = carry;
}

return a;
}

更新:负数的右移是否定义明确?只要满足下面引用的要求,右移负数似乎就可以。

来自 cppreference.com,

For unsigned a and for signed a with nonnegative values, the value of a >> b is the integer part of a/2b . For negative a, the value of a >> b is implementation-defined (in most implementations, this performs arithmetic right shift, so that the result remains negative).

In any case, if the value of the right operand is negative or is greater or equal to the number of bits in the promoted left operand, the behavior is undefined.

最佳答案

假设这是 C 或 C++,你的错误是因为 Left Shifting a negative value is Undefined Behavior , 并且左移一个带符号的值使其变得大于 MAX_INT 也是未定义的行为。

如果您在运行此序列时检查 ab 的值,您将得到:

-1 1
-2 2
-4 4
...
-1073741824 1073741824

此时a&b == 1073741824。但是将它左移 1 与乘以 2 相同,这将得到 2147483648,它大于 INT_MAX。

那是未定义的行为。系统可以选择做任何事情。看来在您的情况下,它进行了移位,给出了 0x80000000。在有符号的 int 中,这表示 INT_MIN。所以在下一次循环中,你试图左移一个负数,这又是未定义的行为。您的系统选择将此视为异常。

一般来说,如果您要进行位操作,最好使用无符号类型。

关于C++ 负数左移溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55615186/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com