0

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 5
    Why were you expecting it to return true? – Hong Ooi Nov 24 '19 at 13:46
  • Do you know the meaning of the `&` operator (as opposed to the `&&` operator)? Do you know the standard binary representation of the integer 7? What [common representations for negative numbers](https://en.wikipedia.org/wiki/Signed_number_representations) exist? What's common today? What's the binary representation of -8 in it? If you answer these basic questions you can answer your specific question here (and all others like it). – Peter - Reinstate Monica Nov 24 '19 at 14:10

2 Answers2

9

-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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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.

DarkAtom
  • 2,589
  • 1
  • 11
  • 27