请解释输出

Sad*_*que 1 c bitwise-operators

#include<stdio.h>

int main(void) 
{
    int a=-3,b=5,c;
    c=a|b;
    printf("%d ",c);
    c=a&b;
    printf("%d ",c);
}
Run Code Online (Sandbox Code Playgroud)

输出是-3 5,请解释一下如何?

Chr*_*ris 7

要了解输出,您需要熟悉用于表示负二进制数的Two's Complement.从+ x到-x的转换实际上非常简单:补充所有位并添加一位.现在假设您的整数长度为8位(足以检查5和-3):

5: 0000 0101
3: 0000 0011 => -3: 1111 1101
Run Code Online (Sandbox Code Playgroud)

现在让我们来看看按位或:

1111 1101 | 0000 0101 = 1111 1101
Run Code Online (Sandbox Code Playgroud)

确切地说-3的再压缩

现在是按位AND:

1111 1101 & 0000 0101 = 0000 0101
Run Code Online (Sandbox Code Playgroud)

正好是5的二进制表示