c++ - 位运算的问题
PHPz
PHPz 2017-04-17 14:57:15
0
4
544
#include <iostream>

using namespace std;

int main()
{
    cout << (0b11 & (~0)) << endl;
    getchar();
    return 0;
}

为什么上面这个代码输出结果是3?就是想问为什么~0可以得到全是1的掩码,为什么不是只有一个1,像这样0000000000000000000001。

PHPz
PHPz

学习是最好的投资!

reply all(4)
大家讲道理

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?

Ty80

Because ~ is bitwise inversion. If all are 0, if you negate each one, they will all be 1

左手右手慢动作

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.

Ty80

0b11 is actually binary literal.
But this is a gcc extension. If you use vc++, it can only be used in 2015 Preview.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template