按位运算符的说明

Sri*_*h R 3 c

我一直在对变量执行按位运算.

int p=3,q=5;
int a=~p,b=~q; //complement a and b
printf("%d %d\t%d %d",p,a,q,b);
Run Code Online (Sandbox Code Playgroud)

'b'的理论输出为10,如果签名,则必须为-2.但输出是-6.

有人可以解释一下它的工作原理吗?

dnl*_*crl 7

~是c(或python)中的按位补码运算符,它基本上是计算的-x - 1.

所以表格看起来像:

0  -1
1  -2
2  -3
3  -4 
4  -5 
5  -6
Run Code Online (Sandbox Code Playgroud)

在二进制补码表示中,如果数字x的最高有效位为1,则实际值为 - (~x + 1).

例如,

0b11110000 = -(~0b1111 + 1) = -(15 + 1) = -16.
Run Code Online (Sandbox Code Playgroud)

这是负数的自然表示,因为

0000001 =  1
0000000 =  0
1111111 = -1  (wrap around)
1111110 = -2
1111101 = -3 etc.
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参见http://en.wikipedia.org/wiki/Two%27s_complement.