0

In the below code,since the bitwise complement of x is -1(using 2's Complement) and y is 2, I am expecting the value of z to be zero but I am getting the value of z as 2 when I run the program.Can anyone please explain me where I am going Wrong?

CODE

#include <stdio.h>
int main()
{
    int x = 0, y = 2;
    int z = ~x & y;
    printf("%d\n", z);
}
Sai Sankalp
  • 451
  • 1
  • 4
  • 14

1 Answers1

4

The bitwise compliment of 0 is all 1s so ANDing with it gives you exactly the other input to the AND, in this case 2.

Assuming 8 bits to save space:

0    = 00000000
~0   = 11111111

2    = 00000010

~0&2 = 00000010
Motti
  • 110,860
  • 49
  • 189
  • 262
  • Is there no need to do 2's complement for zero because whenever we find the complement of a number say for example,we want to find the complement of 2,we get -3 right(Using 2's complement)?So,I was thinking in this case, since the bitwise complement of 0 is -1, we need to bitwise AND -1 and 2?Is it wrong? – Sai Sankalp Jul 03 '16 at 07:50
  • @SaiSankalp bitwise compliment has nothing to do with signed numbers and 2's complement, it's just a bitwise operation. 2's complement determines what bit pattern negative integers will have, so that addition with regular bit-operations will give the correct result. – Motti Jul 03 '16 at 07:54
  • Yeah I have gone through that.So I think I have cleared my doubt. So when we are doing bitwise And operation on a complement of a number with other number, it is enough to just flip the bits of that number and then proceed to bitwise And operation with other number right? – Sai Sankalp Jul 03 '16 at 08:02
  • 1
    @SaiSankalp `~` means flip the bits – M.M Jul 03 '16 at 08:27