Why does if( -8 & 7) return false [duplicate]

2020-02-07 11:15发布

When i try to run the following code it prints "FALSE" instead of "TRUE" Can somebody explain why the code returns false?

#include <stdio.h>

int main(void)
{
    if(-8 & 7)
    {
        printf("TRUE");
    }
    else
    {
        printf("FALSE");
    }
    return 0;
}

2条回答
Rolldiameter
2楼-- · 2020-02-07 11:22

-8 can be represented the following way ( I will use a byte representation

8  = 00001000
~8 = 11110111
-8 = 11111000 (~8 + 1)

That is -8 in the two-complement representation is equal tp ~8 + 1

So -8 is equal to 11111000 and 7 is equal to 00000111

11111000
&
00000111
========
00000000

that is the binary AND operation yields a false result.

查看更多
太酷不给撩
3楼-- · 2020-02-07 11:43

7 is represented as 00000111 in binary. -8 is represented as 11111000 in binary. The bitwise AND operation performs an AND on every bit:

00000111
&
11111000
=
00000000

Hence, the if condition is false.

查看更多
登录 后发表回答