#include <iostream>
using namespace std;
int main()
{
cout << (0b11 & (~0)) << endl;
getchar();
return 0;
}
为什么上面这个代码输出结果是3?就是想问为什么~0
可以得到全是1的掩码,为什么不是只有一个1,像这样0000000000000000000001。
大家讲道理2017-04-17 14:59:15
Assume your environment is 32-bit and int is 4 bytes. 0 is equivalent to 00000000 00000000 00000000 00000000
, '~' bitwise inversion , and we get 11111111 11111111 11111111 11111111
. Also, what is 0b11
? I don't think I've seen this way of writing before?
PHP中文网2017-04-17 14:59:15
Because ~ is bitwise inversion. If all are 0, if you negate each one, they will all be 1
ringa_lee2017-04-17 14:59:15
Since 0b11
is a binary number, the answer is obvious. The result of ~0
is 1, 0b11
is ANDed with 1, and the result remains unchanged, so the result is 3, the decimal result of 0b11
.
PHP中文网2017-04-17 14:59:15
0b11
is actually binary literal.
But this is a gcc extension. If you use vc++, it can only be used in 2015 Preview.