- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
如下图,代码有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 也是未定义的行为。
如果您在运行此序列时检查 a
和 b
的值,您将得到:
-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/
我正在做一个项目,我的 android 在这个项目中作为一个网络服务器工作;输入带端口号的 IP 地址,打开 Web 界面,用户可以将文件上传到手机。我想在 Web 界面上显示一些图片,以便我们的界面
我是一名优秀的程序员,十分优秀!